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

C++ output stream to a file is not working

我的代码如下。缓冲区有数据,但 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

您可能忘记关闭文件。您可以通过

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
    }
}

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

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