相关疑难解决方法(0)

将整个ASCII文件读入C++ std :: string

我需要将整个文件读入内存并将其放在C++中std::string.

如果我把它读成a char[],答案很简单:

std::ifstream t;
int length;
t.open("file.txt");      // open input file
t.seekg(0, std::ios::end);    // go to the end
length = t.tellg();           // report location (this is the length)
t.seekg(0, std::ios::beg);    // go back to the beginning
buffer = new char[length];    // allocate memory for a buffer of appropriate dimension
t.read(buffer, length);       // read the whole file into the buffer
t.close();                    // close file handle

// ... Do stuff with buffer here ...
Run Code Online (Sandbox Code Playgroud)

现在,我想做同样的事情,但是使用a std::string而不是a char[] …

c++ string file-io caching standard-library

559
推荐指数
5
解决办法
49万
查看次数

在C++中将整个文件读入std :: string的最佳方法是什么?

如何将文件读入a std::string,即一次读取整个文件?

文本或二进制模式应由调用者指定.该解决方案应符合标准,便携且高效.它不应该不必要地复制字符串的数据,它应该避免在读取字符串时重新分配内存.

实现此目的的一种方法是统计文件大小,调整大小std::stringfread()进入std::string's const_cast<char*>()' data().这要求std::string数据是连续的,这是标准不需要的,但似乎是所有已知实现的情况.更糟糕的是,如果在文本模式下读取文件,则其std::string大小可能与文件大小不同.

一个完全正确的,符合标准的和便携式解决方案,可以构建使用std::ifstreamrdbuf()进入std::ostringstream,并从那里进入std::string.但是,这可能会复制字符串数据和/或不必要地重新分配内存.所有相关的标准库实现是否足够智能以避免所有不必要的开销?还有另一种方法吗?我是否错过了一些已经提供所需功能的隐藏Boost功能?

请显示您的建议如何实施.

void slurp(std::string& data, bool is_binary)
Run Code Online (Sandbox Code Playgroud)

考虑到上面的讨论.

c++ string file-io

155
推荐指数
10
解决办法
6万
查看次数

标签 统计

c++ ×2

file-io ×2

string ×2

caching ×1

standard-library ×1