Nathaniel Nathaniel - 14 days ago 6
C++ Question

file.write only writing 7 bytes of file in C++

The following code only saves the first 7 bytes to the file correctly and the remaining 3072-7=3065 bytes are incorrect. "correct" meaning the same value as stored in 'data'.

#define byte unsigned char
void bytesToImage(byte width, byte height, byte* data, size_t byte_count, char* fileNameWithoutExtension)
{
{
std::ofstream file("k3000", std::ios::binary);
file.write((char *)data, 3000);
}
}


However this code does save the first 500 bytes correctly:

#define byte unsigned char
void bytesToImage(byte width, byte height, byte* data, size_t byte_count, char* fileNameWithoutExtension)
{
{
std::ofstream file("k500", std::ios::binary);
file.write((char *)data, 500);
}
}


data
has a length of 3072 and the function is called as follows:

size_t imageByteCount = 32 * 32 * 3;
byte* imageBufferOut = (byte*)malloc(sizeof(byte) * imageByteCount);
//(imageBufferOut is initialized...)
bytesToImage(32, 32, imageBufferOut, imageByteCount, "img");


Please excuse the redundant parameters, I have removed as much as possible to try find the bug.

Hex dumps:
enter image description here

Answer

Try adding some more instrumentation. For example:

    {
        cout << "before:";
        for (int i = 0; i < 16; ++i)
            cout << ' ' << std::hex << int(data[i]);
        cout << '\n';

        std::ofstream file("k3000", std::ios::binary);
        if (file)
            cout << "opened\n";
        else
            cout << "couldn't open\n";
        file.write((char *)data, 3000);
        file.flush();
        if (file)
            cout << "wrote ok\n";
        else
            cout << "write failed\n";

        cout << "after:";
        for (int i = 0; i < 16; ++i)
            cout << ' ' << std::hex << int(data[i]);
        cout << '\n';
    }
Comments