tags:

views:

123

answers:

2

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);
}
+8  A: 

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.

Jerry Coffin
ugh :S don't know how did i miss that in the manual, been reading about it in the past 20 minutesThanks!
sekmet64
+2  A: 

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

kaizer.se