Search code examples
cfwrite

How does fwrite work?


I'm trying to write a program in C that scales bitmap images by a given factor, when I use fwrite() inside a loop to do so:

// Go through each pixel of input bitmap
for (int y = 0; y < inWidth; y++)
{
    fread(pixel, sizeof(RGBTRIPLE), 1, inBMP);

    // Write each pixel to output bitmap (factor) times
    for (int z = 0; z < factor; z++)
    {
        fwrite(pixel, sizeof(RGBTRIPLE), 1, outBMP);
    }
}

Everything works:

Input BitmapOutput Bitmap

But when I use fwrite() without a loop:

// Go through each pixel of input bitmap
for (int y = 0; y < inWidth; y++)
{
    fread(pixel, sizeof(RGBTRIPLE), 1, inBMP);

    // Write each pixel to output bitmap (factor) times
    fwrite(pixel, sizeof(RGBTRIPLE), factor, outBMP);
}

I get this:

Output Bitmap

Why does that happen ?


Solution

  • The problem is the third parameter, count, indicates how many elements are in the array pointed to by ptr, not how many times the instance pointed to as ptr should be written. You're basically writing garbage that's in memory behind what's ptr is pointing to.

    See the docs for more details.