从文件中读数据用ifstream
,比如:
#include <iostream>
#include <fstream>
int main(){
std::string file_name = "path/filename.txt";
std::ifstream i_f_stream(file_name); // 申请资源创建i_f_stream句柄
if(!i_f_stream){ // 路径或文件名不对
std::cerr << "file open error" << std::endl;
exit(-1);
}
std::string line; // 读取的内容暂存到line中
std::vector<std::string> file_vector; // 用vector按行保存
while(std::getline(i_f_stream, line)) // 一直读到EOF
file_vector.push_back(line);
i_f_stream.close(); // 用完后需释放资源
}
将数据写入文件用ofstream
,比如:
#include <iostream>
#include <fstream>
int main(){
std::string file_name = "path/filename_txt";
std::ofstream o_f_stream(file_name); // 申请资源,创建ofstream的句柄
//若path不对,则创建失败,path对,ofstream会清空filename.txt的内容,
//并打开filename.txt,若不存在则创建filename.txt
if(!o_f_stream){
std::cerr << "file open error" << std::endl;
exit(-1);
}
for(int i = 0; i < 100; ++i){
o_f_stream << "hello";
o_f_stream << i;
o_f_stream << std::endl;
}
o_f_stream.close(); // 释放资源
return 0;
}
标签:std,txt,ifstream,stream,fstream,filename,file,ofstream
From: https://www.cnblogs.com/langweixianszu/p/18516721