0

I am building a custom shell in c, and one of the requirements is that the folder from while you run the program must be the "home" folder.

That is, if you type in just cd or cd ~ you should get to that directory. I have implemented it, but it is not working.

char *basedir;
void init_prompt()
{
    getcwd(cwd,100);
    basedir = cwd;
}
void cd_me(char **argv)
{
    chdir(argv[1]);
    if(getcwd(cwd,100)!=0)
    {
        ;
    }
    if(strcmp("~\0",argv[1])==0||strcmp("\0",argv[1])==0)
        chdir(basedir);
}

Any suggestions on how to fix this?

Also when I print basedir I am getting the correct output.

Rosie Red
  • 71
  • 5
  • You should `strcmp` to `"~"` or `""`. The trailing null byte is implicit, and comparing to a string with an explicit null byte will never succeed. – tripleee Sep 27 '16 at 05:10
  • 1
    A proper shell will expand `~` to the home directory before any of this happens. – tripleee Sep 27 '16 at 05:11
  • Why are you adding `\0` at the end of each string literal? This is not needed, there's one already in there by default. – n. m. could be an AI Sep 27 '16 at 05:16
  • I changed it in my code.. It still doesn't work. I remain in the same directory. – Rosie Red Sep 27 '16 at 05:24
  • as @tripleee pointed out, "~" are expanded by your shell, see [this stack overflow answer](http://stackoverflow.com/a/1660054/105104) for how it work – dvhh Sep 27 '16 at 05:30
  • 1
    @tripleee: The explicit trailing null bytes are pointless but harmless. The string comparison stops at the first null byte. – Jonathan Leffler Sep 27 '16 at 05:33
  • @tripleee I don't think that happens because I'm writing the whole thing and I haven't given that functionality. – Rosie Red Sep 27 '16 at 05:44

1 Answers1

2
 char *basedir;
 basedir = cwd;

You make basedir a synonym to cwd. Whenever cwd changes, basedir follows. It's a pointer, it cannot remember its own string, it can only point to someone else's string.

You must make a copy instead.

 char basedir[100];
 strcpy(basedir,cwd);

Add bounds checks and error handling as needed.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243