\377 character in c

北战南征 提交于 2019-12-02 01:59:52

问题


i am trying to read a file in c. i have a .txt file and it has that content:

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

when i try to read this file with fopen i get this output:

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

what does \377 mean? Here's my code.

    #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;
    }

回答1:


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.




回答2:


The \377 is an octal escape sequence, decimal 255, all bits set. It comes from converting EOF - which usually has the value -1 - to a char, due to

while (!feof(filelist)) {

feof(filelist) only becoming true after you have tried to read past the file.

So at the end of the file, you enter the loop once more, and the getc() returns EOF.



来源:https://stackoverflow.com/questions/13830338/377-character-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!