Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fread correctly?

Tags:

c

fread

I've seen two ways of providing the size of a file to fread.

If lets say I have a char array data, a file pointer and filesize is the size of the file in bytes then the first is:

fread(data, 1, filesize, file);

And the second:

fread(data, filesize, 1, file);

My question is, is there any difference between the two lines of code?
and which line of code is more "correct".

Also, I'm assuming the 1 in the two lines of code actually means sizeof(char), is that correct?

like image 337
Eden Salomon Avatar asked Nov 15 '25 00:11

Eden Salomon


1 Answers

Argument 2: size of each member

Argument 3: Number of objects you want to read

Now your question:

is there any difference between the two lines of code?

fread(data, 1, filesize, file);

Reads filesize objects pointed by data where size of each object is 1 byte. If less than filesize bytes are read, those would be read partially.

fread(data, filesize, 1, file);

Reads 1 object pointed by data where size of this object is filesize bytes. If less than filesize bytes are available, none would be read.

Do whatever is the requirement of your program.

like image 101
Mohit Jain Avatar answered Nov 17 '25 15:11

Mohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!