ProgNow
ProgNow

Reputation: 55

Why I can not write .ppm P3 file with fwrite on a buffer in C++, only hard-coded text?

Here is the code, but I get error, black image..

FILE* fp = fopen(filename, "wb");
    //fprintf(fp, "P3\n4 4 \n255\n 168  50  50 168  50  51  168  50  51 15  0 15 0  0  0 0 15  7  255 255 255    0  0  0 0  0  0    0  0  0    0 15  7    0  0  0 15  0 15    0  0  0    0  0  0    0  0  0");
    fprintf(fp, "P3\n4 4 \n255 \n");

    unsigned char* newBuffer = (unsigned char*)malloc(4*4*3);

    int br = 0;
    for (int i = 0; i < 4 * 4; i++) {
        newBuffer[br++] = 168;
        newBuffer[br++] = 50;
        newBuffer[br++] = 50;

    }

    fwrite(newBuffer, sizeof(unsigned char), (size_t)(4*4*3), fp);
    fclose(fp);

When I use commented line instead of newBuffer it works perfectly, and I do not know what is the difference when I write bytes in one string and when I write bytes with newBuffer.. Any help, thanks in advance..

Upvotes: 0

Views: 106

Answers (0)

Related Questions