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);
}
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.
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.
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.
read() returns -1 when the end of the file is encountered.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With