#include<iostream>
#include<string>
#include<fstream>
using namespace std;
void test01()
{
fstream file("hfj.txt",ios::out);
file<<"test01"<<123<<endl;
file.close();
}
void test02()
{
fstream file;
file.open("hfj.txt",ios::out);
file<<"test02"<<endl;
file.close();
}
void test02e()
{
fstream file;
file.open("hfj.txt",ios::out|ios::app);
file<<"test02e"<<endl;
file.close();
}
void test03()
{
ofstream file("hfj.txt",ios::app);
file<<"test03"<<endl;
file.close();
}
void read01()
{
fstream file("hfj.txt",ios::in);
if(!file.is_open()) cerr<<"打开文件失败"<<endl;
cout<<"******read01*****"<<endl;
string s;
file>>s;
cout<<s<<endl;
cout<<endl;
file.close();
}
void read02()
{
fstream file;
file.open("hfj.txt",ios::in);
if(!file.is_open()) cerr<<"打开文件失败"<<endl;
cout<<"******read02 while(file>>s)*****"<<endl;
string s;
while(file>>s){
cout<<s<<endl;
}
cout<<endl;
file.close();
}
void read02e()
{
fstream file;
file.open("hfj.txt",ios::in|ios::ate);
if(!file.is_open()) cerr<<"打开文件失败"<<endl;
cout<<"******read02e ios::in|ios::ate*****"<<endl;
string s;
file.seekg(0);
while(file>>s){
cout<<s<<endl;
}
cout<<endl;
file.close();
}
void read03()
{
fstream file("hfj.txt",ios::in);
if(!file.is_open()) cerr<<"打开文件失败"<<endl;
cout<<"******read03 while(file.getline(s,sizeof(s)/sizeof(char)))**"<<endl;
char s[1024];
while(file.getline(s,sizeof(s)/sizeof(char))){
cout<<s<<endl;
}
cout<<endl;
file.close();
}
void read04()
{
fstream file("hfj.txt",ios::in);
if(!file.is_open()) cerr<<"打开文件失败"<<endl;
cout<<"******read04 while((s=file.get())!=EOF)*****"<<endl;
char s;
while((s=file.get())!=EOF){
cout<<s;
}
cout<<endl;
file.close();
}
int main()
{
cout<<"*****文件已经以三种方式写入*****"<<endl;
cout<<endl;
test01();
test02();
test02e();
test03();
read01();
read02();
read02e();
read03();
read04();
system("pause");
return 0;
}
|