c++ - 文件输入输出乱码

标签 c++ filtering boost-iostreams

这两个函数之间的数据变得乱码。检查每一边的变量,数据肯定是不同的。消息大小信号确实有效。这是第二个有问题的读/写函数。 这是我的写入函数及其计数器读取函数:

string Pipe::RecvCompressedMessage()
{
int message_size = 0;
DWORD dwBytesRead = 0;
string buf, data;
byte size_in[sizeof(int)];

if (!ReadFile(_h, &message_size, sizeof(int), &dwBytesRead, NULL))
{
    debug->DebugMessage(Error::GetErrorMessageW(GetLastError()));
    Close();
    return "";
}

if (message_size < 0)
    return "";

buf.resize(message_size);

int total_bytes_read = 0;

while(total_bytes_read < message_size)
{
    if (!ReadFile(_h, (LPVOID) &buf, message_size - total_bytes_read, &dwBytesRead, NULL))
    {
        int err = GetLastError();

        debug->DebugMessage(Error::GetErrorMessageW(GetLastError()));
        Close();
        return "";
    }

    data.append(buf);

    total_bytes_read += dwBytesRead;
}

std::string decompressed;
boost::iostreams::filtering_streambuf<boost::iostreams::output> out;
out.push(boost::iostreams::bzip2_decompressor());
out.push(boost::iostreams::back_inserter(decompressed));
boost::iostreams::copy(boost::make_iterator_range(buf), out);

return decompressed;
}


void Pipe::SendCompressedMessage(string message)
{
std::string compressed;
boost::iostreams::filtering_streambuf<boost::iostreams::output> out;
out.push(boost::iostreams::bzip2_compressor());
out.push(boost::iostreams::back_inserter(compressed));
boost::iostreams::copy(boost::make_iterator_range(message), out);

DWORD dwBytesWritten;
int message_size = compressed.length();

if (WriteFile(_h, &message_size, sizeof(int), &dwBytesWritten, NULL) == 0)
{
    debug->DebugMessage(Error::GetErrorMessageW(GetLastError()));

    Close();
    return;
}

if (WriteFile(_h, (LPVOID *) &compressed, message_size, &dwBytesWritten, NULL) == 0)
{
    debug->DebugMessage(Error::GetErrorMessageW(GetLastError()));

    Close();
    return;
}
}

最佳答案

string buf, data;
...
if (!ReadFile(_h, (LPVOID) &buf, message_size - total_bytes_read, &dwBytesRead, NULL))

您将指向字符串对象的指针作为 lpBuffer 传递给 ReadFile。将字符串替换为 vector:

vector<char> buf;
...
buf.resize(message_size - total_bytes_read);
if (!ReadFile(_h, &buf[0], message_size - total_bytes_read, &dwBytesRead, NULL))

关于c++ - 文件输入输出乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7890999/

相关文章:

c++ - 本地声明的对象的内部内存在范围外完好无损?

javascript - 在 AngularJs 中使用两种过滤器过滤一些数据但不起作用

java - 使用 lambdaj 过滤集合

c++ - 帮助管理 iostream

c++ - LLVM builder::GetInsertBlock,这个函数的作用是什么?

c++ - Qt 中具有高度依赖函数的单元测试

c++ - 使用 boost iostreams 过滤器(关闭且不可复制)

c++ - 使用 CMake 对 boost::iostreams::mapped_file_source::init() 的 undefined reference

c++ - 为什么我的 MFC 应用程序不能完全退出?

javascript - SlickGrid DataView 过滤器功能异常