5

我正在尝试用 c 读取文件。我有一个 .txt 文件,其中包含以下内容:

file_one.txt file_two.txt file_three.txt file_four.txt

当我尝试用 fopen 读取这个文件时,我得到这个输出:

file_one.txt file_two.txt file_three.txt file_four.txt\377

\377 是什么意思?这是我的代码。

    #include <stdio.h>

    #include <stdlib.h>

    int main(int argc, const char * argv[]){

        FILE *filelist;

        char ch;

        filelist=fopen("file-path", "rt");

        while (!feof(filelist)) {
            ch = getc(filelist);
            printf("%c",ch);
        }

        fclose(filelist);

        return 0;
    }
4

2 回答 2

13

\377是一个八进制转义序列,十进制 255,所有位设置。它来自转换EOF- 通常具有价值-1- 到 a char,由于

while (!feof(filelist)) {

feof(filelist)只有在您尝试阅读该文件后才变为真。

所以在文件的最后,你再次进入循环,然后getc()返回EOF.

于 2012-12-11T23:40:36.747 回答
13

The getc() function returns a result of type int, not of type char. Your char ch; should be int ch;.

Why does it return an int? Because the value it returns is either the character it just read (as an unsigned char converted to int) or the special value EOF (typically -1) to indicate either an input error or an end-of-file condition.

Don't use the feof() function to detect the end of input. It returns true only after you've run out of input. Your last call to getc() is returning EOF, which when stored into a char object is converted to (char)-1, which is typically '\377'.

Another problem is that feof() will never return a true value if there was an input error; in that case, ferror() will return true. Use feof() and/or ferror() after getc() returns EOF, to tell why it returned EOF.

To read from a file until you reach the end of it:

int ch;
while ((ch = getc(filelist)) != EOF) {
    /* ch contains the last character read; do what you like with it */
}

Suggested reading: Section 12 of the comp.lang.c FAQ.

于 2012-12-11T23:41:17.973 回答