Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

unix

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);
}
like image 368
sekmet64 Avatar asked Jul 05 '10 14:07

sekmet64


People also ask

What does read () return at end-of-file?

The read() method of the input stream classes reads the contents of the given file byte by byte and returns the ASCII value of the read byte in integer form. While reading the file if it reaches the end of the file this method returns -1.

How do I read end-of-file?

The function feof() is used to check the end of file after EOF. It tests the end of file indicator. It returns non-zero value if successful otherwise, zero.

What does the function read () do?

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file.

Which of the expressions can be used to discover that read () invocation reached end-of-file?

read() returns -1 when the end of the file is encountered.


2 Answers

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.

like image 97
Jerry Coffin Avatar answered Oct 13 '22 17:10

Jerry Coffin


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

like image 32
u0b34a0f6ae Avatar answered Oct 13 '22 16:10

u0b34a0f6ae