在C++中写入二进制文件时出错
我尝试打开一个二进制文件进行读写(标志: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;
}
谢谢。
抱歉我的英语不好:-)
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 :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要正确定位写入指针:
You need to position the write pointer correcty: