简体   繁体   English

C ++ io的奇怪行为

[英]Strange behavior with c++ io

I am using zlib to compress data for a game I am making. 我正在使用zlib压缩我正在制作的游戏的数据。 Here is the code I have been using 这是我一直在使用的代码

#include <SFML/Graphics.hpp>
#include <Windows.h>
#include <fstream>
#include <iostream>
#include "zlib.h"
#include "zconf.h"

using namespace std;

void compress(Bytef* toWrite, int bufferSize, char* filename)
{
    uLongf comprLen = compressBound(bufferSize);
    Bytef* data = new Bytef[comprLen];
    compress(data, &comprLen, &toWrite[0], bufferSize);
    ofstream file(filename);
    file.write((char*) data, comprLen);
    file.close();
    cout<<comprLen;
}

int main()
{
    const int X_BLOCKS = 1700;
    const int Y_BLOCKS = 19;
    int bufferSize = X_BLOCKS * Y_BLOCKS;
    Bytef world[X_BLOCKS][Y_BLOCKS];
    //fill world with integer values
    compress(&world[0][0], bufferSize, "Level.lvl");
    while(2);
    return EXIT_SUCCESS;
}

Now I would have expected the program to simply compress the array world and save it to a file. 现在,我希望程序可以简单地压缩数组世界并将其保存到文件中。 However I noticed a weird behavior. 但是我注意到一个奇怪的行为。 When I prited the value for 'comprLen' it was a different length then the created file. 当我使用'comprLen'值时,它的长度与创建的文件的长度不同。 I couldn't understand where the extra bytes in the file were coming from. 我不明白文件中多余字节的来源。

You need to open the file in binary mode: 您需要以二进制模式打开文件:

std::ofstream file(filename, std::ios_base::binary);

without the std::ios_base::binary flag the system will replace end of line characters ( \\n ) by end of line sequences ( \\n\\r ). 如果没有std::ios_base::binary标志,系统将用行尾( \\n\\r )替换行尾字符( \\n )。 Suppressing this conversion is the only purpose of the std::ios_base::binary flag. 禁止此转换是std::ios_base::binary标志的唯一目的。

Note that the conversion is made on the bytes written to the stream. 请注意,转换是对写入流的字节进行的。 That is, the number of actually written bytes will increase compared to the second argument to write() . 也就是说,与write()的第二个参数相比,实际写入的字节数将增加。 Also note, that you need to make sure that you are using the "C" locale rather than some locale with a non-trivial code conversion facet (since you don't explicitly set the global std::locale in your code you should get the default which is the "C" locale). 另请注意,您需要确保使用的是"C"语言环境,而不是使用具有非平凡代码转换方面的语言环境(因为您没有在代码中显式设置全局std::locale ,默认为"C"语言环境)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM