如何使用chdir系统功能

How to use chdir system function

我正在尝试使用 chdir 更改我的进程的工作目录。假设我的当前目录中有一个 apple 目录。为什么我在提示中输入apple 返回的结果是-1?是不是因为我输入apple的时候,'\n'字符也放在了字符串的末尾? 另外,如果我只能用一个变量来存储它,那么改变目录有什么意义?

#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>

int main(void){
    char path[256];
    fgets(path, 256, stdin);
    printf("%s", path);
    int result = chdir(path);
    if(result != 0){
        printf("%d\n", result);
    }
}

fgets() 为结果添加后缀 可能(如果没有收到 EOF)读取新行(\n on IXish系统)并将其传递给 chdir() 会使后者窒息,因为要更改为大多数 likley 的目录名称不带有尾随换行符。

来自 man fgets()我用斜体字):

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.


关于调试的注意事项:如果您将要打印的 "string"(如 fgets() 所读)放在这样的引号中

printf("'%s'", path);

您可能已经注意到尾随 \n