2

I'm trying to read a binary file on Windows 7 with a program compiled by MinGW. The binary file is ~10M in size but my program can only read less than 1000 bytes and it thinks it reached EOF.

Here is the code. I'm sure I'm doing something stupid but I just can't seem to find it.

#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #define TS_FILE "foo.data" int main(void) { int fd; int r; unsigned char buf[1024]; fd = open(TS_FILE, O_RDONLY|O_BINARY); printf("fd: %d\n", fd); if ( fd == -1 ) { exit(0); } for (;;) { r = read(fd, buf, 1000); if ( r != 1000 ) { printf("read error. %d\n", r); perror("read"); } if ( r == 0 ) { break; } } close(fd); } 

The program will say it reads 736 bytes and that's the EOF.

Could somebody tell me what is going on? Thanks!

Thanks,

1 Answer 1

1

In fact, your program is indeed reading the entire file. It reads the file 1000 bytes at a time until there are, in this case, 736 bytes left. Then it reads those final 736 bytes and read returns 736. You are mistakenly treating the inability to read the full 1000 bytes as an error, but it is not an error. If read fails then the error condition is marked by the return value being -1.

Your loop should perhaps be more like this:

for (;;) { r = read(fd, buf, 1000); if (r == -1) { printf("read error\n"); perror("read"); exit(1); } if (r != 1000) { //entire file has been read break; } } close(fd); 

A couple of other points:

  1. The correct type for r is size_t.
  2. Rather than hardcoding 1024 and 1000, you would be better with something like #define BUFFLEN 1024 so that you don't keep repeating those magic values.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.