c++ 一次读取文件全部内容

180it 2020-10-10 AM 1531℃ 0条

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

读取一个string
std::ifstream in("some.file");
std::string some_str;
in >> some_str;

这种方法的问题在于,遇到回车空格等分隔符的时候,就不会再读取了。

读取文件全部内容
iostream著名专家Dietmar Kuehl给出了两个读取方法

std::ifstream in("some.file");
std::isreambuf_iterator begin(in);
std::isreambuf_iterator end;
std::string some_str(begin, end);

std::ifstream in("some.file");
std::ostringstream tmp;
tmp << in.rdbuf();
std::string str = tmp.str();

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

c++ 一次读取文件全部内容