C中的字符串解析

dev*_*vin 0 c string

我正在尝试将字符串传递给chdir().但我似乎总是有一些尾随的东西使chdir()失败.

#define IN_LEN  128

int main(int argc, char** argv) {

    int counter;
    char command[IN_LEN];
    char** tokens = (char**) malloc(sizeof(char)*IN_LEN);
    size_t path_len; char path[IN_LEN];

      ...

    fgets(command, IN_LEN, stdin) 
    counter = 0;
    tmp = strtok(command, delim);
    while(tmp != NULL) {
        *(tokens+counter) = tmp;
        tmp = strtok(NULL, delim);
        counter++;
    }

    if(strncmp(*tokens, cd_command, strlen(cd_command)) == 0) {
        path_len = strlen(*(tokens+1));
        strncpy(path, *(tokens+1), path_len-1); 
    // this is where I try to remove the trailing junk... 
    // but it doesn't work on a second system
        if(chdir(path) < 0) {
            error_string = strerror(errno);
            fprintf(stderr, "path: %s\n%s\n", path, error_string);
}

// just to check if the chdir worked
char buffer[1000];
    printf("%s\n", getcwd(buffer, 1000));

    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

必须有更好的方法来做到这一点.有什么帮助吗?我试图使用scanf但是当程序调用scanf时,它只是挂起.

谢谢

Ste*_*e K 5

看起来你忘了在调用strncpy()之后向路径字符串添加一个空的'\ 0'.如果没有null终止符,chdir()就不知道字符串的结束位置,只是一直找到它.这会使您看起来路径末尾有多余的字符.