How to correctly set size and count parameters for fwrite() to write a chunk of bytes? [duplicate]

StackOverflow https://stackoverflow.com/questions/21379436

  •  03-10-2022
  •  | 
  •  

Question

Looking at the spec for fwrite(const void * ptr, size_t size, size_t count, FILE * stream), I'm unsure what exactly goes into the size parameter and the count parameter when writing binary data, i.e. a chunk of bytes.

Do I have to tell fwrite to write bufLen blocks of size 1, or should I tell it to write 1 block of size bufLen? Is any of these better? How does it affect the returned value? How does it affect the behaviour in the case of an error?
If I specify to write one block of size bufLen, does it always write either the complete data or nothing?

In code, it looks like this:

char* buf = ...;
int bufLen = ...;
FILE* file = ...;

/* alternative 1: */ int writtenByteCount = fwrite(buf, 1, bufLen, file);
/* alternative 2: */ int writtenByteCount = fwrite(buf, bufLen, 1, file);

printf("fwrite wrote %i of %i bytes/blocks", writtenByteCount, bufLen);

if (writtenByteCount < bufLen) {
    // handle error
}
Was it helpful?

Solution

The fwrite() function shall write, from the array pointed to by ptr, up to nitems elements whose size is specified by size, to stream.

For each object( nitems times for a fwrite() call), size calls shall be made to the fputc(), taking the values (in order) from an array of unsigned char exactly overlaying the object.

As long as the underlying writes are buffered (which is commonly the case for most filesystems), the difference in performance of both the cases will be quite negligible.

The file-position indicator for the stream (if defined) shall be advanced by the number of bytes successfully written. If an error occurs, the resulting value of the file-position indicator for the stream is unspecified.


How the two variants differ is when partial writes are performed and fwrite() returns. Then having a smaller size and larger nitems provides a higher granularity in the return value.

For example if ONLY 5 bytes were written (in an attempt to write 10 bytes),

// case 1
fwrite(bufptr, 1, 10, fptr);
// returns 5. As 5 out of 10 items written successfully

// case 2
fwrite(bufptr, 10, 1, fptr);
// returns 0. As 0 out of 1 item written
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top