0

Is there any difference between the below lines of code?

fread(&buf, sizeof(int), 10,infile);

and

for (int i = 0, i < 10, i++)
{
    fread(&buf, sizeof(int), 1,infile);
}

If so (or not so) then why?

Thanks in advance.

1 Answer 1

1

The most obvious difference is the return value: fread returns the number of elements read (in this case, the number of sizeof(int)'s). If all goes well, the first formulation will return 10, while the sum of the individual fread return values (each having a return value of 1) in the second formulation should likewise equal 10.

Also, if the stream (infile) has less than the number of elements you specify (in this case, 10), or if there is an error before the full number of elements is read (usually when it reaches EOF) the first formulation will return an error while the second formulation will tell you how many elements were read (if you change for loop and instead tell it to read in subject to condition !feo(infile) and tally the number of fread return values in the loop).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .