c++ - 在 C++ 中写入二进制文件时出错

标签 c++ binary fstream

我尝试打开二进制文件进行读写(标记: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;
}

谢谢。

抱歉我的英语不好 :-)

最佳答案

您需要正确定位写指针:

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

关于c++ - 在 C++ 中写入二进制文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5693243/

相关文章:

即使 gcount 返回 0,C++ iostream 也不会设置 eof 位

c++ - 将 C++ 中的数据保存到用户无法访问的文件中?

c++ - 无法从文件中读取值

c++ - OpenGL 3/GLFW 空白视口(viewport)

math - 如何查找具有以下约束的二进制数的个数:

ruby-on-rails - 如何在 Rails 5 中获取上传图像的二进制数据?

c++ - 从 .so/.o 文件获取 c/cpp 中的静态库列表

c++ - 通过析构函数删除动态成员导致程序挂起

c++ - ptree get_value,名称包括 “.”

c# - Windows shell 扩展 : context menu when more than 16 files are selected