I've been trying to compress strings and save them to text files, then read the data and decompress it. When I try to decompress the read string, however, I get a Z_BUF_ERROR (-5) and the string may or may not decompress.
In the console, I can compress/decompress all day:
std::string s = zlib_compress("HELLO asdfasdf asdf asdfasd f asd f asd f awefo@8 892y*(@Y");
std::string e = zlib_decompress(s);
The string e
will return the original string with no difficulty.
However, when I do this:
zlib_decompress(readFile(filename));
I get a Z_BUF_ERROR
. I think it might be due in part to hidden characters in files, but I'm not really sure.
Here's my readFile
function:
std::string readFile(std::string filename)
{
std::ifstream file;
file.open(filename.c_str(), std::ios::binary);
file.seekg (0, std::ios::end);
int length = file.tellg();
file.seekg (0, std::ios::beg);
char * buffer = new char[length];
file.read(buffer, length);
file.close();
std::string data(buffer);
return data;
}
When I write the compressed data, I use:
void writeFile(std::string filename, std::string data)
{
std::ofstream file;
file.open(filename.c_str(), std::ios::binary);
file << data;
file.close();
}
If needed, I'll show the functions I use to de/compress, but if it works without the File IO, I feel that the problem is an IO problem.