- 论坛徽章:
- 0
|
如何使用c++的fstream对文件读写操作(库函数)
我有两个实现,一个是通过使用list,将文件中的所有数据检索出来处理,然后在回填到文件中.但是比较吃内存(都要导出到内存中这个实现简单就不说了,
还有一种实现,如下:
#include <fstream>;
#include <string>;
#include <iostream>;
//specifies the operating system
//因为dos中文本文件格式0d 0a回车换行
//unix下只有od
#ifndef DOS
#define DOS
#endif
#ifdef UNIX
#undef UNIX
#endif
using namespace std;
void main()
{
int ID = 1;
string name;
streampos preGP=0;
streampos insPP = 0;
int i=0;
fstream fout("aaa.txt", ios::in|ios:ut);
preGP=fout.tellg(); //获取检索下一个数据前的位置
cout<<i<<" pos: "<<preGP<<endl;
fout>;>;ID>;>;name;
while(!fout.eof())
{
if (ID == 200)
{
cout<<"the id = 100 the origan name : "<<name<<endl;
name = "testas";
//#ifdef DOS
fout.seekp(preGP+streampos(2), ios::beg);
//#endif
/*#ifdef UNIX
fout.seekp(preGP+streampos(1), ios::beg);
#endif*/
insPP = fout.tellp();
cout<<"the insert data pos: "<<insPP<<endl;
fout<<ID<<" "<<name<<endl;
}
preGP = fout.tellg(); //获取检索下一个数据前的位置
cout<<++i<<" pos: "<<preGP<<endl;
fout>;>;ID>;>;name;
}
fout.flush();
fout.close();
cout<<"test.log ok"<<endl;
}
但是存在这样一个问题如果新name的数据很长例如:"testaaaaaaaaaaaaffffffff", 那么新的数据就会覆盖掉id = 300以及后面的数据.或许这样也更容易理解为什么数据库中要求指定数据段的长度,必须在一个范围内,否则就可能覆盖掉后面的数据,而在oracle中如果某字段是char(20).值"hello",他也会自动填充空格进去"hello "使其长度为20
是否有一种方法可以直接 bbb覆盖调并且保持
300 ... 等后面的数据不被覆盖.并且其name长度是任意的
请教
我的文件中的数据如下:
100 aaa
200 bbb
300 ccc
400 ddd |
|