我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
现在我希望程序能够简单地压缩数组世界并将其保存到文件中.但是我发现了一种奇怪的行为.当我为'comprLen'命名时,它与创建的文件的长度不同.我无法理解文件中额外字节的来源.
您需要以二进制模式打开文件:
std::ofstream file(filename, std::ios_base::binary);
Run Code Online (Sandbox Code Playgroud)
如果没有该std::ios_base::binary标志,系统将用\n行序列末尾()替换行尾字符(\n\r).抑制此转换是该std::ios_base::binary标志的唯一目的.
请注意,转换是在写入流的字节上进行的.也就是说,与第二个参数相比,实际写入的字节数将增加write().另请注意,您需要确保使用的是"C"区域设置而不是某些具有非平凡代码转换方面的区域设置(因为您没有std::locale在代码中显式设置全局,您应该获得默认值,即"C"区域设置) .
| 归档时间: |
|
| 查看次数: |
45 次 |
| 最近记录: |