4

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?

2
  • 2
    Learn to look up the proper manual of the libraries you're using. See here for the complete detail on fread. Commented Jul 14, 2015 at 9:49
  • I did look at the manual, specifically here link. But I was still uncertain because I saw both ways in working code. Commented Jul 15, 2015 at 9:16

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The first tells fread to read elements of size 1, filesize of them.

The second tells fread to read filesize elements of size of 1.

In theory both produce the same result.

Comments

0

In practice and theory both produce the same result. But if you respect the 'fread' standard, the first line is the correct one.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.