我試圖傳遞一個字符串到chdir()。但我似乎總是有一些尾隨的東西使得chdir()失敗。C中的字符串解析
#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;
}
必須有更好的方法來做到這一點。有任何幫助嗎?我試圖使用scanf,但是當程序調用scanf時,它只是掛起。
感謝
啊是的。多麼愚蠢的錯誤。非常感謝。我感到非常沮喪。 – devin 2009-09-02 21:11:43
如果我每次犯了一個愚蠢的編程錯誤,都會有鎳...... – 2009-09-02 21:18:39