fread() question.

Goi

Diamond Member
Oct 10, 1999
6,771
7
91
Hi,
I'm trying to read from a binary file in blocks of constant size(say 512B), and then write it into another file, with fread() and fwrite(). However, if the original filesize is a multiple of 512, I'm always reading an extra block, and if it's not a multiple of 512, my final block will contain partial data, which will then be written to an output file that is a multiple of 512.

I'm doing a while (0 == feof(file)) and within that loop, a fread(&buffer, 512,1,file). How do I eliminate the final block problem? I'm guessing I'll have to find out the size of the data within the blocks and check if it's <512, but I'm not sure how to do that.
 

Templeton

Senior member
Oct 9, 1999
467
0
0
fread will return the actual amount of data read, just check this and you'll know what to write.
 

Goi

Diamond Member
Oct 10, 1999
6,771
7
91
I thought so, but according to the fread man pages, the return value is the number of items read, which in the example code I provided, is 1. Do I use a fread(&buffer, 512, 512, file) instead? That seems weird.
 

Templeton

Senior member
Oct 9, 1999
467
0
0
Sorry, you're right, I didn't look at your post close enough. Is there a particular reason why you can't do:
fread(&buffer, 1, 512, file)?
 

Goi

Diamond Member
Oct 10, 1999
6,771
7
91
Well, I haven't tried that, but again according to the man pages, the 2nd field should be the size in bytes that I want to read, and since I wanted to read data in 512B chunks, I put 512 in that field. Sounds intuitive enough, until I realize what the return value was. I was just wondering what the standard way of doing this would be, coz the method you're proposing looks a bit like a hack ;)
 

Templeton

Senior member
Oct 9, 1999
467
0
0
The second field is the size of the elements you'll be reading. The standard way would be to read the desired number of elements(specified by 3rd arg) and give as the second arg the size of an element in the file. You cannot read a partial element from a file, if you specify that an element is of size 512B, then the smallest element you can read in is 512B. If your file has elements of size 1B, the the method above is the correct way to read 512 of them. (or any number less then this)