同一个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;
}
#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;
}
#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;
}