user3717474
user3717474

Reputation: 57

fwrite function in C

fwrite function is used for writing in binary.

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

here size in "size_t size" represent byte i.e. fwrite() writes nmemb elements of data, each "size" bytes long.

"size" can be 1 byte or can be more. So for int which is of 2 bytes, if we gave 'size' 1 byte, how that integer is written? May be written integer is wrong? Or we should take care of it while writing integer and set value of size equal to 2?

Upvotes: 4

Views: 2600

Answers (3)

R Sahu
R Sahu

Reputation: 206717

When you write an int array using fwrite, you will need to use:

size_t num = fwrite(array, sizeof(int), arraySize, file);
if ( num != arraySize )
{
    // Deal with the error condition.
}

Upvotes: 6

Andras
Andras

Reputation: 3055

fwrite has a weird interface, but all it does is writes size * nmemb bytes. You can write (ptr, 1, 4, fp) or (ptr, 4, 1, fp) and you'll get the same output.

if you write (ptr, 1, 1, fp) you'll get the byte at the lowest memory address. On a little-endian machine, that is the least significant byte of the int. On a big-endian machine, it's the most significant byte.

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 60027

The number of bytes written will be nmemb * size.

But for ints you would write

fwrite(buffer, sizeof(int), number_of_ints, file);

(as the size of ints is compiler dependent - usually 4 bytes)

Upvotes: 4

Related Questions