为什么 opendir() 对一个字符串有效而不对另一个字符串有效?

Why does opendir() work for one string but not another?

我想使用 opendir 打开一个目录,但我看到了一些意外的东西。 opendir 适用于从 getcwd 返回的字符串,但不适用于我的辅助函数 read_cwd 返回的字符串,即使这些字符串看起来相等。

如果我打印字符串,都打印 /Users/gwg/x,这是当前工作目录。

这是我的代码:

char real_cwd[255];
getcwd(real_cwd, sizeof(real_cwd));

/* This reads a virtual working directory from a file */
char virt_cwd[255];
read_cwd(virt_cwd);

/* This prints "1" */
printf("%d\n", strcmp(real_cwd, virt_cwd) != 0);

/* This works for real_cwd but not virt_cwd */
DIR *d = opendir(/* real_cwd | virt_cwd */);

这是 read_cwd 的代码:

char *read_cwd(char *cwd_buff)
{
    FILE *f = fopen(X_PATH_FILE, "r");
    fgets(cwd_buff, 80, f);
    printf("Read cwd %s\n", cwd_buff);
    fclose(f);
    return cwd_buff;
}

fgets() 包括换行符。

Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character. — http://en.cppreference.com/w/c/io/fgets


像这样读取输入时,您应该 trim 字符串两端的白色 space。

来自 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. A terminating null byte (aq[=11=]aq) is stored after the last character in the buffer.

您需要从正在读入的字符串中删除换行符。

函数 fgets 在缓冲区中包含最后一个换行符——所以第二个字符串实际上是 "/Users/gwg/x\n".

解决此问题的最简单(但不一定是最干净)的方法是用 '[=13=]' 覆盖换行符:在函数 read_cwd 的末尾添加以下内容:

n = strlen(cwd_buff);
if(n > 0 && cwd_buff[n - 1] == '\n')
    cwd_buff[n - 1] = '[=10=]';