在c ++中将整个文件读入std :: string的最好方法是什么? [英] What is the best way to read an entire file into a std::string in c++?

查看:324
本文介绍了在c ++中将整个文件读入std :: string的最好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将文件读入 std :: string ,即一次读取整个文件?文本或二进制模式应由调用者指定。该解决方案应符合标准,便携和高效。它不应该不必要地复制字符串的数据,并且应该避免在读取字符串时重新分配内存。

How to read a file into a std::string, i.e., read the whole file at once? Text or binary mode should be specified by the caller. The solution should be standard-compliant, portable and efficient. It should not needlessly copy the string's data, and it should avoid reallocations of memory while reading the string.

一种方法是stat文件大小, std :: string fread()插入 std :: string ' const_cast< char *>()'ed data()。这要求 std :: string 的数据是连续的,这是标准不需要的,但似乎是所有已知实现的情况。更糟糕的是,如果以文本模式读取文件, std :: string 的大小可能不等于文件的大小。

One way to do this would be to stat the filesize, resize the std::string and fread() into the std::string's const_cast<char*>()'ed data(). This requires the std::string's data to be contiguous which is not required by the standard but appears to be the case for all known implementations. What is worse, if the file is read in text mode, the std::string's size may not equal the file's size.

可以使用 std :: ifstream rdbuf()转换为 std :: ostringstream ,然后从 std :: string 。然而,这可以复制字符串数据和/或不必要地重新分配存储器。所有相关的标准库实现足够聪明,以避免所有不必要的开销?还有别的办法吗?

Fully correct, standard-compliant and portable solutions could be constructed using std::ifstream's rdbuf() into a std::ostringstream and from there into a std::string. However, this could copy the string data and/or needlessly reallocate memory. Are all relevant standard library implementations smart enough to avoid all unnecessary overhead? Is there another way to do it? Did I miss some hidden boost function that already provides the desired functionality?

请显示您的建议如何实施

Please show your suggestion how to implement

void slurp(std::string& data, bool is_binary)


推荐答案

最快的(我知道,打折内存映射文件):

And the fastest (that I know of, discounting memory-mapped files):

string str(static_cast<stringstream const&>(stringstream() << in.rdbuf()).str());

这需要额外的标题< sstream> 为字符串流。
static_cast 是必要的,因为运算符<< 返回一个普通的 ostream& 但是我们知道,现实中它是一个 stringstream& 所以这个转换是安全的。)

This requires the additional header <sstream> for the string stream. (The static_cast is necessary since operator << returns a plain old ostream& but we know that in reality it’s a stringstream& so the cast is safe.)

拆分成多行,将临时变量转换为变量,我们得到一个更易读的代码:

Split into multiple lines, moving the temporary into a variable, we get a more readable code:

string slurp(ifstream& in) {
    stringstream sstr;
    sstr << in.rdbuf();
    return sstr.str();
}

或者,再次在一行中:

string slurp(ifstream& in) {
    return static_cast<stringstream const&>(stringstream() << in.rdbuf()).str();
}

这篇关于在c ++中将整个文件读入std :: string的最好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆