我正在使用zlib压缩我正在制作的游戏的数据。这是我一直在使用的代码
#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;
}
现在,我希望程序可以简单地压缩数组世界并将其保存到文件中。但是我注意到一个奇怪的行为。当我使用'comprLen'值时,它的长度与创建的文件的长度不同。我不明白文件中多余的字节是从哪里来的。
您需要以二进制模式打开文件:
std::ofstream file(filename, std::ios_base::binary);
如果没有该std::ios_base::binary
标志,则系统将用行尾(\n
)替换行尾字符(\n\r
)。禁止这种转换是该std::ios_base::binary
标志的唯一目的。
请注意,转换是对写入流的字节进行的。也就是说,与的第二个参数相比,实际写入的字节数将增加write()
。还要注意,您需要确保使用的是"C"
语言环境,而不是使用具有非平凡代码转换方面的语言环境(因为您没有std::locale
在代码中显式设置全局变量,因此应该获得默认"C"
语言环境) 。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句