方法一
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
ifstream ifs("test.txt");
string content( (istreambuf_iterator<char>(ifs) ),
(istreambuf_iterator<char>() ) );
cout << content << endl;
ifs.close();
return 0;
}
方法二
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
ifstream ifs("test.txt");
// get the size of file
ifs.seekg(0, ios::end);
streampos length = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> buffer(length);
if (ifs.read(buffer.data(), length)) {
// process
ofstream out("output.txt");
out.write(buffer.data(), length);
out.close();
}
ifs.close();
return 0;
}
方法三
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
std::string contents(buffer.str());
// process
t.close();
return 0;
}