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

标签 c++ string caching file-io standard-library

<分区>

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

如果我将其读入 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 ...

现在,我想做完全相同的事情,但使用 std::string 而不是 char[]。我想避免循环,即我不想想:

std::ifstream t;
t.open("file.txt");
std::string buffer;
std::string line;
while(t){
std::getline(t, line);
// ... Append line to buffer and go on
}
t.close()

有什么想法吗?

最佳答案

有两种可能性。我喜欢的一个使用 stringstream 作为中间人:

std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();

现在,“file.txt”的内容可以作为 buffer.str() 的字符串使用。

另一种可能性(虽然我当然也不喜欢它)更像你原来的:

std::ifstream t("file.txt");
t.seekg(0, std::ios::end);
size_t size = t.tellg();
std::string buffer(size, ' ');
t.seekg(0);
t.read(&buffer[0], size); 

正式来说,这不需要在 C++98 或 03 标准下工作(字符串不需要连续存储数据),但实际上它适用于所有已知的实现,C++11 和更高版本可以需要连续存储,因此可以保证与它们​​一起工作。

至于为什么我也不喜欢后者:首先,因为它更长且更难阅读。其次,因为它要求你用你不关心的数据初始化字符串的内容,然后立即覆盖该数据(是的,与读取相比,初始化的时间通常是微不足道的,所以它可能无关紧要,但对我来说仍然感觉有点不对)。第三,在文本文件中,文件中的位置 X 并不一定意味着您已经阅读了 X 个字符才能到达该位置——不需要考虑行尾翻译之类的事情。在进行此类翻译的真实系统(例如,Windows)上,翻译后的形式比文件中的内容短(即,文件中的“\r\n”在翻译后的字符串中变为“\n”)所以你所做的一切保留了一些您永远不会使用的额外空间。同样,并没有真正造成重大问题,但无论如何感觉有点不对劲。

关于c++ - 将整个 ASCII 文件读入 C++ std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10661425/

相关文章:

css - W3 Total Cache 更新style.css需要做什么?

java - C std::string 作为带有 SWIG 的 Java 中的输出参数

android - 在 XML 中连接多个字符串?

c++ - 来自wav文件的数据在-1和1之间,c++,sndfile

c - 如何将指针赋值给全局变量?

c - 为什么C语言中string const的地址这么小,总是在同一个地址

Android 应用程序的缓存

java - Crate 连接查询花费太多时间

c++ - Xcode:使用 32 位库编译 64 位应用程序

c++ - 如何在 C++ 中检测 map 中给定位置的面积?