zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++ 读取文件所有内容的方法

C++文件方法 内容 所有 读取
2023-09-14 09:07:08 时间

方法一

#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;
}