What are the two arguments to fread?

When reading the documentation for fread

here , it explains that the two arguments after void *ptr

are multiplied together to determine the number of bytes read / written to the file. Below is the function header for the linked fread

link:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

      

My question, apart from the return value from the function, is there really a difference in behavior or performance between calling each one:

// assume arr is an int[SOME_LARGE_NUMBER] and fp is a FILE*
fread(arr, sizeof(arr), 1, fp);
fread(arr, sizeof(arr) / sizeof(int), sizeof(int), fp);
fread(arr, sizeof(int), sizeof(arr) / sizeof(int), fp);
fread(arr, 1, sizeof(arr), fp);

      

And which one will usually be the best practice? Or a more general question: how can I decide what to specify for each of the arguments in any given scenario?

EDIT

To clarify, I am not asking for justification of two arguments instead of one, I am asking for a general approach to deciding what to pass to arguments in any given scenario. And this answer that Massimiliano, linked in the comments and quoted, contains only two specific examples and does not sufficiently explain why this is happening.

+3


source to share


1 answer


There is a difference in behavior if there is not enough data to satisfy the request. From the page you link to:

The total number of elements read successfully is returned as a size_t object, which is an integral data type. If this number is different from the nmemb parameter, then either an error occurred or the end of file was reached.

So, if you specify that there is only one dimension element sizeof(arr)

and there is arr

not enough data to fill , then you will not get any data returned. If you do:



fread(arr, sizeof(int), sizeof(arr) / sizeof(int), fp);

      

it arr

will be partially filled if the data is insufficient.

The third line of your code most naturally matches the API fread

. However, you can use one of the other forms if you document why you are not doing the normal thing.

+3


source







All Articles