开发者

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

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.

#include <stdio.h>开发者_运维百科;
#include <fcntl.h>
int main() {

  // writing binary numbers to a file
  int fd = open("afile", O_WRONLY | O_CREAT, 0644);
  int i;
  for (i = 0; i < 10; i++) {
    write(fd, &i, sizeof(int));
  }
  close(fd);

  //trying to read them until EOF
  fd = open("afile", O_RDONLY, 0);
  while (read(fd, &i, sizeof(int)) != EOF) {
    printf("%d", i);
  }
  close(fd);
}


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜