1

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:");
        }
    }
4

2 回答 2

5

如果输入的行是这样的:

cd xyzzy

然后目录从偏移量 3 开始,而不是 2。此外,fgets通常会在最后为您提供一行带有换行符的行,因此您也需要将其删除,例如:

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

您可能应该更智能地标记输入,例如bash(例如)这样的外壳具有相当复杂的规则。

于 2013-05-04T17:19:08.893 回答
1

后面可能有一个空格字符"cd",所以你应该加 3 而不是 2。

    printf("\nGOT = %s\n",(arguments+3));
    ret = chdir ((arguments+3));
于 2013-05-04T17:16:34.353 回答