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

前端 未结 3 2220
不知归路
不知归路 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:05

    You must check for errors. On some (common) errors you want to call read again!

    If read() returns -1 you have to check errno for the error code. If errno equals either EAGAIN or EINTR, you want to restart the read() call, without using its (incomplete) returned values. (On other errors, you maybe want to exit the program with the appropriate error message (from strerror))

    Example: a wrapper called xread() from git's source code

    0 讨论(0)
  • 2020-12-17 20:06

    read returns the number of characters it read. When it reaches the end of the file, it won't be able to read any more (at all) and it'll return 0, not EOF.

    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题