file.write只用C ++编写7个字节的文件

时间:2016-11-19 21:58:03

标签: c++ pointers io

以下代码仅将前7个字节正确保存到文件中,剩余的3072-7 = 3065个字节不正确。 "正确"表示存储在'数据'中的相同值。

#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);
    }
}

但是,此代码确实正确保存了前500个字节:

#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的长度为3072,函数调用如下:

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

请原谅冗余参数,我已经删除了尽可能多的尝试找到错误。

十六进制转储: enter image description here

1 个答案:

答案 0 :(得分:1)

尝试添加更多的工具。例如:

    {
        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';
    }