一次读入全部文件到内存中

用string 存储文件内容

    std::fstream fin("file_name",std::fstream::in);
    std::string file_data_str;
    if(fin.good()) {
        std::stringstream ss;
        ss<<fin.rdbuf();
        fin.close();
        file_data_str=ss.str();
    }

用vector存储文件内容

std::fstream fin("fine_name",std::fstream::in|std::fstream::ate);
    size_t file_size=fin.tellg();
    fin.seekg(0,std::fstream::beg);
    std::vector<char> file_data_vec(file_size,0);
    if(fin.good()) {
        fin.write(file_data_vec.data(),file_size);
        fin.close();
    }

用unique_ptr存储文件内容

std::fstream fin("fine_name",std::fstream::in|std::fstream::ate);
    size_t file_size=fin.tellg();
    fin.seekg(0,std::fstream::beg);
    std::unique<char[]> file_data_uptr(new char[file_size]{0});
    if(fin.good()) {
        fin.write(file_data_uptr.get(),file_size);
        fin.close();
    }
原文地址:https://www.cnblogs.com/smallredness/p/10935964.html