GreenPenguin
GreenPenguin

Reputation: 311

fread() fails to read file data in Dev-Cpp

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!

Upvotes: 1

Views: 1270

Answers (1)

melpomene
melpomene

Reputation: 85887

If you're reading a binary file, you should open it with "rb", not "r". Otherwise you get (platform specific) "text mode" handling. On Linux this doesn't change anything, but on Windows this will translate CR/LF (0D 0A) to '\n' and may also interpret ^Z as the end of the file.

You can confirm this by looking at a hex dump of the file: If your program mysteriously stops reading at 1A, this is the problem.

Upvotes: 2

Related Questions