0

I try to open a binary file for both reading and writing (flag: ios_base::binary | ios_base::in | ios_base::out).

My file already exists and its content is: 123

There is no problem in reading of the file, but writing the file does not work after closing the file. The file content has no change. It seems fstream.write() does not work correctly.

I use VS2010.

Code:

#include <iostream>
#include <fstream>
using namespace std;

int main (void) 
{
    fstream stream;

    // Opening the file: binary + read + write.
    // Content of file is: 123
    stream.open("D:\\sample.txt", ios_base::binary | ios_base::in | ios_base::out);

    // Read 1 bye.
    char ch;
    stream.read(&ch, 1/*size*/);

    // Check any errors.
    if(!stream.good())
    {
        cout << "An error occured." << endl;
        return 1;
    }

    // Check ch.
    // Content of file was: 123
    if(ch == '1')
    {
        cout << "It is correct" << endl;
    }

    // Write 1 bye.
    ch = 'Z';
    stream.write(&ch, 1/*size*/);

    // Check any errors.
    if(!stream.good())
    {
        cout << "An error occured." << endl;
        return 1;
    }

    // Close the file.
    stream.close();

    // OHhhhhhhhhhh:
    // The content of file should be: 1Z3
    // but it is: 123

    return 0;
}

Thanks.

Sorry for my pooooooor English :-)

1 Answer 1

3

You need to position the write pointer correcty:

stream.seekp( 1 );
stream.write(&ch, 1/*size*/);
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I'm wondering too, doesn't stream.read() move the pointer already?
There is only one file position, shared between reading and writing. Therefore you have to position it each time you change mode.
It seems in binary read and write mode, before any write we shoud add this code: stream.seekp(stream.tellp());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.