How to use read() to read data until the end of the file?

前端 未结 3 2252
不知归路
不知归路 2020-12-17 19:41

I\'m trying to read binary data in a C program with read() but EOF test doesn\'t work. Instead it keeps running forever reading the last bit of the file.

#in         


        
3条回答
  •  孤城傲影
    2020-12-17 20:09

    POSIX rasys return == 0 for end of file

    http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html

    If no process has the pipe open for writing, read() shall return 0 to indicate end-of-file.

    This confirms Jerry's answer.

    EOF is returned by some ANSI functions, e.g. man getc says:

    fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

    ungetc() returns c on success, or EOF on error.

    so you still can't use it to distinguish error and end of file in that case, feof is needed.

    See also: How to use EOF to run through a text file in C?

提交回复
热议问题