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.
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.