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