16

So I'm not entirely sure how to use fread. I have a binary file in little-endian that I need to convert to big-endian, and I don't know how to read the file. Here is what I have so far:

FILE *in_file=fopen(filename, "rb");
char buffer[4];
while(in_file!=EOF){
    fread(buffer, 4, 1, in_file);
    //convert to big-endian.
    //write to output file.
}

I haven't written anything else yet, but I'm just not sure how to get fread to 'progress', so to speak. Any help would be appreciated.

AndreyAkinshin
  • 18,603
  • 29
  • 96
  • 155
user202925
  • 521
  • 2
  • 5
  • 16
  • Complete the program and run it! `fread` will read from where it left off the last time round the loop. You should check the return value from `fread`. `infile` is not likely to compare equal to `EOF`. – luser droog Mar 29 '13 at 05:23
  • 1
    For one, "rb" means **R**ead **B**inary, so your array should be of type int, not char. – MarcusJ May 04 '15 at 21:26
  • 9
    I actually disagree. The array should be chars. Binary characters are only a single byte while an integer is 4 bytes. So in this case using a char array would be a better representation because one char represents one byte. – Ian Leaman Feb 27 '16 at 21:07

1 Answers1

33

That's not how you properly read from a file in C.

fread returns a size_t representing the number of elements read successfully.

FILE* file = fopen(filename, "rb");
char buffer[4];

if (file) {
    /* File was opened successfully. */
    
    /* Attempt to read */
    while (fread(buffer, sizeof *buffer, 4, file) == 4) {
        /* byte swap here */
    }

    fclose(file);
}

As you can see, the above code would stop reading as soon as fread extracts anything other than 4 elements.

Chnossos
  • 9,971
  • 4
  • 28
  • 40
user123
  • 8,970
  • 2
  • 31
  • 52
  • 4
    I suggest `while (fread(buffer, 1, 4, file) == 4) { ... }` in order to ensure that 4 bytes are read and avoid the undefined behaviour of using uninitialised values. – autistic Mar 29 '13 at 05:32
  • Thanks for bringing that up. I just realized that I should be using 1 for the size and 4 for the count. Also, awesome name bro! – user123 Mar 29 '13 at 05:33
  • 1
    Indeed. I hadn't noticed that, however. My comment was in regards to explicitly comparing the return value to 4, rather than 0, because if fread were to return 3, 2 or 1 then there would be uninitialised bytes in buffer, which would result in undefined behaviour if those values were used. – autistic Mar 29 '13 at 05:36
  • but what if the file has say 4 characters? – space_mill Jan 07 '22 at 04:36