写文件
#include<fstream>
ofstream wf;
wf.open("1.txt"); // 等价于 ofstream wf("1.txt");
wf << "John T Smith 90\n";
wf << "Eric K Jones 95\n";
wf.close();
读文件
string fn, ln;
char mi;
int score;
ifstream input("1.txt");
input >> fn >> mi>>ln >> score;
cout<<fn<<" "<<mi<<ln<<" "<<score<<endl;
input >> fn >> mi>>ln >> score;
cout<<fn<<" "<<mi<<ln<<" "<<score<<endl;
input.close();
cout<<"Done"<<endl;
检测文件是否存在
写文件如果不存在,会自动创建,读文件则不行
ifstream input;
input.open("1.txt");
if(input.fail()){
cout<<"File does not exist\n"<<endl;
}
检测文件末尾
ifstream input("1.txt");
double sum = 0;
double num = 0;
while(input >> num)
sum += num;
让用户输入文件名 检测文件是否存在,这里需要注意的就是需要把string类型转换为char数组
string filename;
cout<<"Enter a filename: ";
cin>>filename;
ifstream input(filename.c_str()); // open函数必须要cstring数组
if(input.fail())
cout<<filename<<" does not exist"<<endl;
else
cout<<filename<<" exists"<<endl;
函数getline get put
ifstream input("state.txt");
if(input.fail()){
cout<<"File does not exist. "<<endl;
}
string city;
while(!input.eof()){
getline(input, city, '#'); // # 表示间隔符号
cout<<city<<endl;
}
input.close();
在文件中追加
fstream add;
add.open("state.txt", ios::app | ios::out);
add<<"Savannah Austin Chicago"<<endl;
add.close();