C++ 读取文件全部内容

C++ 读取文件全部内容

方法一

#include 
#include 
#include 
using namespace std;
int main(int argc, char** argv) {
	ifstream ifs("config.json");
	string content( (istreambuf_iterator<char>(ifs) ),
					 (istreambuf_iterator<char>() ) );
	cout << content << endl;
	ifs.close();
				 
	return 0;
}

方法二

#include 
#include 
using namespace std;
int main(int argc, char** argv) {
	ifstream ifs("config.json");
	// 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   
#include   
#include   
using namespace std;
int main(int argc, char** argv) {
    std::ifstream t("config.json");  
    std::stringstream buffer;  
    buffer << t.rdbuf();  
    std::string contents(buffer.str());
    // process

    t.close();
    return 0;
}

你可能感兴趣的:(C/C++,c++,开发语言)