小编pho*_*an1的帖子

将文件读入 std::string 的最有效方法是什么?

我目前这样做,最后转换为 std::string 需要 98% 的执行时间。一定会有更好的办法!

std::string
file2string(std::string filename)
{
    std::ifstream file(filename.c_str());
    if(!file.is_open()){
        // If they passed a bad file name, or one we have no read access to,
        // we pass back an empty string.
        return "";
    }
    // find out how much data there is
    file.seekg(0,std::ios::end);
    std::streampos length = file.tellg();
    file.seekg(0,std::ios::beg);
    // Get a vector that size and
    std::vector<char> buf(length);
    // Fill the buffer with the size
    file.read(&buf[0],length);
    file.close();
    // return buffer as string
    std::string s(buf.begin(),buf.end());
    return s;
}
Run Code Online (Sandbox Code Playgroud)

c++ string file-io

3
推荐指数
2
解决办法
8813
查看次数

标签 统计

c++ ×1

file-io ×1

string ×1