C++输出流到文件不起作用

C++ output stream to a file is not working

本文关键字:不起作用 文件 输出流 C++      更新时间:2023-10-16

我的代码在下面。缓冲区有数据,但 fout2.write 不做任何事情。文件已创建,并且为空。

ofstream fout2(fname, ios::binary);
fout2.open(fname, ios::binary | ios::in | ios::out);
if (fout2.is_open()) {
    //problem is here   //write the buffer contents
    fout2.write(rmsg.buffer, rmsg.length);
    fout2.flush();
    memset(rmsg.buffer, 0, sizeof(rmsg.buffer)); //clear the buffer

如果你打算同时做输入和输出,正如你使用 ios::in 所暗示的那样,你应该使用 fstream ,而不是ofstream 。然后你应该在构造函数中传递所有开放模式,并且不需要调用open()

fstream fout2(fname, ios::binary | ios::in | ios::out);

您可能忘记关闭文件。你可以通过以下方式做

fout2.close()

或者通过简单地关闭 fout2 的范围:

{
    ofstream fout2(fname, ios::binary);
    fout2.open(fname, ios::binary | ios::in | ios::out);
    if (fout2.is_open()) {
         fout2.write(rmsg.buffer, rmsg.length);
         //out2.flush(); // no need for this
         memset(rmsg.buffer, 0, sizeof(rmsg.buffer)); //clear the buffer
    }
}