0

I'm writing the code for resizing the image . I have an issue while using the fwrite function.

fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

From what I understand the parameter count indicates how many times the value in buffer must be written. However when I use it in the following manner,

fwrite(&triple, sizeof(RGBTRIPLE), n, outptr); where n = 2

I get the following result:

0000036: 00ff00 000000 00ff00 000100  ............
0000042: 00ff00 000200 000000 000000  ............
000004e: 00ff00 000000 ffffff 000100  ............
000005a: 00ff00 000200 000000 000000  ............
0000066: 00ff00 000000 00ff00 000100  ............
0000072: 00ff00 000200 000000 000000  ............

Although, when I use a for loop construct for fwrite:

for(int k = 0; k < n; k++) {
    fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
}

I get my desired output:

0000036: 00ff00 00ff00 00ff00 00ff00  ............
0000042: 00ff00 00ff00 000000 000000  ............
000004e: 00ff00 00ff00 ffffff ffffff  ............
000005a: 00ff00 00ff00 000000 000000  ............
0000066: 00ff00 00ff00 00ff00 00ff00  ............
0000072: 00ff00 00ff00 000000 000000  ............

Why does substituting n for count return those odd hex values viz. 000100, 000200?

1 Answer 1

2

The reason is that the third parameter is NOT the number of times to write out the contents of buffer. It's the number of ELEMENTS, the second parameter (the size of an element) to be written. For illustration, let's say that we're working with letters.

Say that source is a char array and contains abcdef.

Now, say that you had this: fwrite(source, 2, 3, target);. The first parameter says use the first char in source as the starting point.

Your logic says that the fwrite would write out ababab, starting at the first character, and writing 2 chars 3 times.

The reality is that it will write abcdef. It will start at the beginning, but will write 3 elements of 2 chars, or 6 consecutive chars.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Ah, that explains it. Thank you! Commented Jul 14, 2016 at 7:13

You must log in to answer this question.

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