C — using chdir() function

Aviram Fireberger picture Aviram Fireberger · May 4, 2013 · Viewed 19.6k times · Source

I'm trying to use chdir() function but can't work it out.

I'm reading from user and find out if he is using "cd". I always get an error. What am I doing wrong?

Code:

    int * status=0;
    char * buf = 0;
    char arguments[2048];
    buf = getcwd(buf,PATH_MAX);
    printf("%s >",buf);

    fgets(arguments,2048,stdin);

    if( strncmp(arguments,"quit",4)==0 ){
      printf("Exit...\n");
      break;
    }
    else if(strncmp(arguments,"cd",2)==0 ){
        int ret;
        printf("\nGOT = %s\n",(arguments+2));
        ret = chdir ((arguments+2));
        if(ret!=0){
          perror("Error:");
        }
    }

Answer

paxdiablo picture paxdiablo · May 4, 2013

If the line being entered is something like:

cd xyzzy

then the directory starts at offset 3, not 2. In addition, fgets usually gives you a line with a newline character at the end so you'll want to remove that as well, such as:

if (strlen (line) > 0)
    if (line[strlen (line) - 1] == '\n')
        line[strlen (line) - 1] = '\0';

You should probably be tokenising the input a little more intelligently, a shell like bash (for example) has rather complex rules.