读书人

同一个fstream对象如何读写同一个文件

发布时间: 2013-07-08 14:13:00 作者: rapoo

同一个fstream对象怎么读写同一个文件.txt
正在学C++的文件操作,在企图fstream类来进行文件的读取与修改的时候遇到问题了。
不知道可不可以用fstream,交替的读写文件。纠结了很长时间,希望高人能直接给个答案。。。

我想要的结果就是:打开一个文件,读取字符,将特定的字符替换。
比如:
文件内容(随意):
----------
12345678
12344
41422334
---------

将所有 4 这个字符,换成 A。得到:
----------
123A5678
123AA
A1A2233A
---------
先看程序说话吧,
程序1:


#include<iostream>
#include<fstream>
using namespace std;

int main()
{
fstream fio("out.dat",ios::in | ios::out);
//事先建好了文件
if(fio.fail())
{
cout<<"error!"<<endl;
}
char a[20];
while(fio.getline(a,20,'\n'))
{ //先一行一行读出来
int i=0;
cout<<a<<endl;
for(;a[i++]!='\0';)
{
if('4' == a[i])
{
a[i]='A';
}
} //改成想要的字符串
int n = fio.tellg();
fio.seekg(n-strlen(a)-2);
fio<<a; //写回去
cout<<a<<endl;
fio.seekg(n);
}
fio.close();
return 1;

}


输出结果是:(最后一行没有变化)
-------------
123A5678
123AA
41422334
-------------


程序2:
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
fstream fio("out.dat",ios::in | ios::out);
//事先建好文件,内容随意,比如 123456
if(fio.fail())
{
cout<<"error!"<<endl;
}
char c;
//位置一
fio.seekg(0);
while(!fio.eof())
{
c=fio.get();
cout<<c<<" ";
}
fio.seekg(0);//预计的结果:文件内容变成 AB3456
fio.put('A');//但是文件内容完全没有改变,读取文件正常
fio.put('B');//但是把这三行放到位置一,即先写后读的话便可以了。

fio.close();
return 1;

}



问题总结:
1、怎样用一个fstream对象,多次读取与写入文件
(问题背景假设是一个很大的数据文件,其中部分内容需要修改,所以应该不可以全部读出来修改再放入。在此基础上,如果可以用多个对象来实现的方案,我也接受)

2、关于修改文件操作,不知道一般的做法是什么。
[解决办法]
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
fstream fio("out.dat",ios::in
[解决办法]
ios::out);
//事先建好了文件
if(fio.fail())
{
cout<<"error!"<<endl;
}
char a[20];
int i;
while(1)
{
if(fio.eof())
break;
int pos1=fio.tellg();
fio.getline(a,20,'\n');
int pos2=fio.tellg();


cout<<a<<endl;
for(i=0;a[i]!='\0';++i)
{
if('4' == a[i])
{
a[i]='A';
}
}
fio.seekp(pos1);
fio<<a<<'\n';
}
fio.close();

system("pause");
return 0;
}


[解决办法]
有这个还会死循环??
if(fio.eof())
break;

c++的流我很少用, 都是直接用c库或者 api库的, 你说的那种功能
用 fseek 或者 SetFilePointer 都可以设置文件指针 位置
[解决办法]
void ReplaceFile()
{
//fstream 对象打开文件
//读取每个字符,当读取到指定字符时,记录位置插入到vector中
//移动文件指针到指定位置,修改字符
fstream file("d://file2.txt");
vector<int> position;
position.push_back(1);
char cRead='0';
int count=0;
if(file)
{
while(file>>cRead)
{
count++;
if(cRead=='a')
position.push_back(count);
}
file.clear();
file.seekp(fstream::beg);

vector<int>::iterator iter=position.begin()+1,itEnd=position.end();
for(;iter!=itEnd;iter++)
{
file.seekp(*iter-1,fstream::beg);
file<<'A';
}
}
}

读书人网 >C++

热点推荐