【问题标题】:Error in writing binary files in C++用 C++ 编写二进制文件时出错
【发布时间】:2011-04-17 11:31:58
【问题描述】:

我尝试打开一个二进制文件进行读写(标志:ios_base::binary | ios_base::in | ios_base::out)。

我的文件已经存在,其内容是:123

读取文件没有问题,但是关闭文件后写入文件不起作用。文件内容没有变化。看来 fstream.write() 不能正常工作。

我用的是VS2010。

代码:

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

谢谢。

对不起,我的英语很糟糕:-)

【问题讨论】:

    标签: c++ binary fstream


    【解决方案1】:

    你需要正确定位写指针:

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

    【讨论】:

    • 是的,我也想知道,stream.read() 不是已经移动指针了吗?
    • 只有一个文件位置,读写共享。因此,每次更改模式时都必须定位它。
    • 似乎是二进制读写模式,在任何写入之前我们应该添加这个代码:stream.seekp(stream.tellp());
    猜你喜欢
    • 1970-01-01
    • 2015-11-29
    • 2017-10-20
    • 1970-01-01
    • 2019-03-27
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多