I am running into a strange situation. I use Dev C++ to write the following program:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
FILE *fp; // edited -- wrong type at first (File)
unsigned char a, b;
int c, count, res; // added "res"
short int d;
fp = fopen("record.dat", "r");
fseek(fp, SEEK_SET, 0);
count = 0; // edited -- wrong variable name at first
res = fread(&a, 1, 1, fp);
printf("a res = %d, errno %d\n", res, errno);
while(count < 10) {
count++;
res = fread(&b, 1, 1, fp); // added "res =" as mentioned in comment
printf("b res = %d, errno %d\n", res, errno);
res = fread(&c, 4, 1, fp); // added "res =" as mentioned in
printf("c res = %d, errno %d\n", res, errno);
res = fread(&d, 2, 1, fp); // added "res =" as mentioned in
printf("d res = %d, errno %d\n", res, errno);
res = fread(&a, 1, 1, fp); // ** where problem starts
printf("a res = %d, errno %d\n", res, errno);
}
fclose(fp);
}
The "record.dat" file is over 1MB in size, so I suppose the above program can get the data of the first 10 records without any issue (e.g. no need to handle EOF
issue). However, when I compile the program in Dev C++ and run it, after reading 4 records, the fread()
(marked by ** above) returns 0, and then subsequent fread()
inside the while loop also return 0, meaning no data can be read. The stranger thing is all errno
are 0, and when I use a g++ compiler in Linux to compile the same program, the program can read all (not just 10) of the records in the same file without any problem.
Is there anything I have missed? Thanks!
res =
before most of yourfread()
s, making theprintf()
s following them possibly misleading.