(1)
//读入文件中的数,将其输出,并且找出最大的,再写入到文件中去
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream file;
int x=0,max=0;
file.open("c:\\a.txt",ios::in|ios::out); //以读写方式打开文件,默认也是这种方法
if(file.fail())
{
cout<<"file open fail!"<<endl;
}
else{
cout<<"the file informantion is :";
while(file>>x)
{
cout<<x<<" ";
if(x>max) max=x;
}
/*好像没有效果
cout<<endl;
cout<<file.tellp()<<endl;
file.seekg(ios_base::beg); //重新定位到文件开头
if(file.eof())
{
cout<<"file is end!"<<endl;
}
*/
cout<<endl;
cout<<"the file max is: "<<max<<endl;
}
file.close();
return 0;
}
(2)
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
fstream file;
ifstream ifile;
int count=0,icount=0;
string str,istr;
file.open("c:\\a.txt",ios::in|ios::out); //以读写方式打开文件,默认也是这种方法
if(file.fail())
{
cout<<"file open fail!"<<endl;
}
else{
file.write((char *)&count,sizeof(int));
cout<<"-- 请输入收件人邮箱 --"<<endl;
while(cin>>str&& str!="-1")
{
file<<str<<' ';
count++;
}
long pos=file.tellp();
file.seekp(ios_base::beg);
file.write((char *)&count,sizeof(int));
file.seekp(pos);
cout<<"--- 请输入发件人邮箱 ----"<<endl;
if(cin>>str)
{
file<<str;
}
}
file.close();
ifile.open("c:\\a.txt");
if(ifile.fail())
{
cout<<"file open fail!"<<endl;
}
else{
ifile.read((char *)&icount,sizeof(int));
cout<<"-- 收件人邮箱 --"<<endl;
for(int i=0;i<icount;i++)
{
ifile>>istr;
cout<<istr<<endl;
}
cout<<"--- 发件人邮箱 ----"<<endl;
ifile>>istr;
cout<<istr<<endl;
}
ifile.close();
return 0;
}