简体   繁体   中英

Strange behavior with c++ io

I am using zlib to compress data for a game I am making. 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. 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 ). Suppressing this conversion is the only purpose of the std::ios_base::binary flag.

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() . 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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