纰缪绸缪

c++常见文件读写的处理

常见的文本文件处理,包括读和写。

读文本文件

#include <ifstream>
#include <stdexcept>
#include <string>
using namespace std;
string fileName("/foo/bar.txt");
string line;
ifstream myFile(fileName.c_str());
if (not myFile or not myFile.is_open()) {
    throw runtime_error(string("error open ") + fileName);
}
 
while (not myFile.eof()) {
    getline(myFile, line);
    // do what you want with line
}

写入文本文件

#include <ofstream>
#include <stdexcept>
#include <string>
using namespace std;
string fileName("/foo/bar.txt");
string line;
ofstream myFile(fileName.c_str());
if (not myFile or not myFile.is_open()) {
    throw runtime_error(string("error writing when open ") + fileName);
}
 
int a = 2;
myFile <<"line 1" << endl;
myFile << "line " << a << endl;
0 comments
Submit comment