简体   繁体   中英

Error in writing binary files in C++

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 :-)

You need to position the write pointer correcty:

stream.seekp( 1 );
stream.write(&ch, 1/*size*/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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