zoukankan      html  css  js  c++  java
  • C++ 读取文件所有内容的方法

    方法一

    #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;
    }
    
    
  • 相关阅读:
    [考试]20150811
    [考试]20150810
    [随笔]暑假过了,暑假来了
    [考试]20150808
    动态规划大合集II
    [知识点][旧版]C++中的运算符
    NOIP动态规划大合集
    [考试]20150729
    [考试]20150728
    /=============分隔线=============/
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7506909.html
Copyright © 2011-2022 走看看