c++|文件操作

写文件

#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();
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容