0

I use zlib library to compress data from strings and get compressed data also in strings. I load and unload compressed data using fstream. The problem is that sometimes it happens that when a line is written to a file, it becomes one byte larger and I cannot understand why this happens. I checked a row with compressed data and it has the correct size, and I can get decompressed data from it in program without writing in file. Because in the file it turns out one character more, I can no longer decompress this data. When reading such a line from a file, it is accordingly one character more as shown in a text editor.

Output from console

enter image description here

There are "Sel" says what string size is 82.

This is example of my function which puts compressed string into file:

std::fstream file(filename, std::ios::out, std::ios::binary);
if (!file.is_open()) {
    std::cout << "Unable to open file: " << filename << std::endl;
    return;
}

std::stringstream someData;

...puts data in "someData"...

std::string compressedData = Compress_String(someData.str());

std::cout << "Comp string: " << compressedData << std::endl;
std::cout << "Comp size: " << compressedData.size() << std::endl;

file << compressedData;

file.close();

1 Answers1

2

I'm surprised that the following line even compiles.

std::fstream file(filename, std::ios::out, std::ios::binary);

Your compiler must support a non-standard constructor. What you need is

std::fstream file(filename, std::ios::out | std::ios::binary);
//                                       ^^^
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Either than or it applies the comma-operator `:)` – David C. Rankin Dec 11 '19 at 07:03
  • @DavidC.Rankin, The comma operator should not be applied in a function call :) – R Sahu Dec 11 '19 at 07:10
  • Yes, yes, all those little limitation like `"cannot appear in contexts where a comma is used to separate items"`. Kinda takes the fun out of it `:)` – David C. Rankin Dec 11 '19 at 07:39
  • @RSahu, I'm sorry, I didn’t understand what the problem was, that I even tried to record through the fwrite(), and from fatigue I didn’t notice that I was using the open function incorrectly. The main point was to record in binary mode, thanks :D – Dre4msNoEvil Dec 11 '19 at 18:32
  • 1
    @Des4ttempt, don't worry too much about it. Most of us have been through such moments. Happy coding. – R Sahu Dec 11 '19 at 18:56
  • @DavidC.Rankin, it will fun to explore all the things you cannot do just for the heck of it :) We will never run out of options. – R Sahu Dec 11 '19 at 18:58