简体   繁体   English

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

[英]C++ output stream to a file is not working

My code is below. 我的代码如下。 The buffer has the data but fout2.write does not do anything. 缓冲区中有数据,但是fout2.write不执行任何操作。 The file is created and it is empty. 文件已创建,并且为空。

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

You may have forgotten to close the file. 您可能忘记了关闭文件。 You may either do it by 您可以这样做

fout2.close()

Or by simply closing the scope of the fout2: 或通过简单地关闭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
    }
}

If you plan to do both input and output, as implied by your use of ios::in , you should use fstream , not ofstream . 如果打算使用ios::in暗示要同时进行输入和输出,则应使用fstream ,而不要使用ofstream Then you should pass all the open modes in the constructor, and you don't need to call open() . 然后,您应该在构造函数中传递所有打开模式,而无需调用open()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM