cd command usage in C

8.6k Views Asked by At

Hey I'm designing my shell in C as a school project.But I'm stuck with cd command usage in this shell .

Here is the related explanation:

cd <directory> — change the current default directory to <directory>. `

If the <directory> argument is not present, report the current directory.

If the directory does not exist an appropriate error should be reported. You need to support relative and absolute paths. This command should also change the PWD environment variable.

I get path like this:

const char *path = getenv("PATH");//get the system's path 

Here is the main part that I'm planning to fill out:

  else if(strcmp(argsexec[0], "cd") == 0) {
            if(argsexec[1]== NULL){
            system("pwd");//Reporting current directory.
            }
            else if(strcmp(argsexec[1],"..") == 0);
            /**HERE Go to upper directory.          
            }
            else {
            /**HERE Case for cd <directory> go to that directory
            }
        }

How can these HERE parts be achieved?

2

There are 2 best solutions below

0
On BEST ANSWER

you can use these function to implement your function:

   char *getcwd(char *buf, size_t size);
   char *getwd(char *buf);
   char *get_current_dir_name(void);
   int chdir ( const char *path );
   int fchdir ( int fd );
0
On

When you want it easy, just execute chdir(argsexec[1]) (and you do not need to handle the '..' case separately).

When you want it more complicated, you have to handle symbolic links. E.g. when there is a /lib -> /usr/lib symlink, users might expect after cd /lib/somedir && cd .. to be in / but not in /usr. To handle this case, you will have to keep track of the logical path and to implement .. traversals.