请教一个c++问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 12:25:30
在文件流输入的时候,总是把新的内容代替旧的内容,但我只想添加数据进去,原来的我想保留,不想删除,也不想修改,如果把它们读出来再写进去,又感觉很麻烦,有什么办法能够在不修改原有数据的前提下,再写入数据呢?

打开文件的时候以app方式打开就可以了,意为append,就是添加新内容不修改原来的。如:

ofstream out("file", ios::app);
...

#include <fstream>
#include <string>
#include <iostream>
#include <iomanip>

using namespace stdl;

int main()
{
ifstream fin("mytest.txt");
int num = 0;
if(!fin) return 1;
string word;
while(!fin.eof())
{
fin>>word;
num++;
}
fin.close();
ifstream ff("mytext.txt", ios_base::binary);
ff.seekg(0L, ios_base::end);
long size = ff.tellg();
ff.close();
cout<<setw(10)<<"Words"<<setw(10)<<"Size"<<endl;
cout<<setw(10)<<num<<setw(10)<<size<<endl;
return 0;

}