Avatar ·

如何在 C++ 中将整个 ASCII 文件读取到 std::string 中?

大家好!我是一名初学 C++ 的开发者,遇到了一个看似简单但找不到优雅解决方案的问题。我需要将文本 ASCII 文件的内容读取到 std::string 对象中,以便后续将其作为整体数据块处理(例如,用于解析配置或缓存)。 目前我使用的是这样一段笨重的代码: ```cpp #include #include #include std::string readFile(const std::string& filename) { std::ifstream file(filename); std::string content; char ch; while (file.get(ch)) { content += ch; } return content; } ``` 这段代码能工作,但我担心两点: 1. **性能**。逐个字符地追加非常慢。每次调用 `operator+=` 都可能触发内存重新分配。 2. **代码美观**。在 Python 中,我可以一行写成 `open('file.txt').read()`。难道 C++ 标准库中没有类似的东西吗?