返回信息流RT
向文件中连续写了两个相同结构体的对象后重新启动程序并向文件内修改了第一个对象的部分数据,结果发现把文件之前保存的数据全覆盖了,不明白怎么回事...
这是一条镜像帖。来源:北邮人论坛 / cpp / #13533同步于 2008/10/6
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
关于文件中数据重输入后以前的数据会丢失的问题
Cloudeagle
2008/10/6镜像同步7 回复
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
这是第一次向文件中写入对象的代码:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class test
{
public:
int i;
char a;
};
int main()
{
ofstream f("D:\\test.dat");
if(f.fail()) { cout<<"Cannot open file!"<<endl; return 0;}
test t1;
t1.i=5;
t1.a='c';
test t2;
t2.a='d';
t2.i=6;
test t3;
t3.i=7;
t3.a='e';
f<<t1.i;
f<<t1.a;
f<<t2.i;
f<<t2.a;
f<<t3.i;
f<<t3.a;
f.close();
return 0;
}
这是第2次写入的代码:
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class test
{
public:
int i;
char a;
};
int main()
{
ofstream f("D:\\test.dat");
if(f.fail()) { cout<<"Cannot open file!"<<endl; return 0;}
test t1;
t1.i=10;
f<<t1.i;
f.close();
return 0;
}
原意只是想修改第一个对象的第一个数据,结果发现原文件中的数据全被修改了...
不知道为什么?
【 在 ericyosho 的大作中提到: 】
: 文件输入输出就是这样工作的,没有为什么。
: 你第二次打开文件的时候,直接就往里面写了一个t1的数据,整个文件的内容就是t1了。
文件读写不是向里面追加数据吗? 怎么会覆盖了原来的数据呢?
你从哪里知道是追加数据?
你打开了追加标志符么?
【 在 lblz 的大作中提到: 】
: 文件读写不是向里面追加数据吗? 怎么会覆盖了原来的数据呢?
这好像不是写对象吧,
就是普通的写文本吧
【 在 Cloudeagle 的大作中提到: 】
: 这是第一次向文件中写入对象的代码:
: #include<iostream>
: #include<string>
: ...................