Haya Raed
Haya Raed

Reputation: 6221

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

Upvotes: 0

Views: 800

Answers (2)

Barmar
Barmar

Reputation: 780798

If you plan to do both input and output, as implied by your use of ios::in, you should use fstream, not ofstream. Then you should pass all the open modes in the constructor, and you don't need to call open().

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

Upvotes: 1

Michael K
Michael K

Reputation: 36

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:

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

Upvotes: 1

Related Questions