strchr()查找似乎没有任何位置的“ \ n”

时间:2018-10-06 12:56:37

标签: c macos clang fgets strchr

我正在使用一个名为s_gets()的经过修改的fgets()函数,该函数从输入中删除换行符或丢弃输入缓冲区中的任何剩余字符。看起来如下;

char *s_gets(char *str, int n, FILE *pf) {

    char *ret_val;
    char *find;

    ret_val = fgets(str, n, pf);
    if (ret_val) {
        find = strchr(str, '\n');
        if (find) {
            puts("Newline was found.");
            printf("Character before \\n is %c\n", *(find - 1));
            *find = '\0';
        } else {
            while (getchar() != '\n')
                continue;
        }
    }
    return ret_val;
}

当我使用此函数并将FILE*传递给仅包含字符串apple的文件时,if子句中的puts()运行,而{{1 }}语句显示printf()。我的问题是,这个神秘的换行符是从哪里来的?这与EOF有什么关系吗?我正在使用macOS 10.14上的Apple LLVM版本10.0.0(clang-1000.10.44.2)对此进行编译。

1 个答案:

答案 0 :(得分:3)

即使字符串“ apple”写在一行上,编辑器也会自动将换行符添加到该行的末尾(例如,gedit)。那就是为什么你看到它。


PS:如rici所述:Why should text files end with a newline?