c++中一个将文本文件读入std::string的单行代码
A one-liner to read text file into std::string in c++?
是否有一行代码将(不是很大的)文本文件的内容读取为字符串?
我找到的最短的:
#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
(对于大文件,这是一个非常低效的解决方案,因为它必须在从流中读取每个新字符后重新分配缓冲区)
将整个ASCII文件读取为c++ std::string您可以在一条语句中完成:
std::string str(std::istreambuf_iterator<char>(std::ifstream("file.txt").rdbuf()), std::istreambuf_iterator<char>());
这是不是一行代码取决于你的显示器有多大
请注意不适合大文件
而不是"不适合大文件"我宁愿说它是极其低效的解决方案,因为它必须在从流中读取新字符时反复重新分配缓冲区。
还要注意,在这种情况下,代码的行数是您应该最不注意的指标之一。一旦有了ifstream
对象(其名称应该比t
更有意义),
你应该检查它的状态,是否为is_open()
,更合理的读取方法似乎是这种方法:
// obtain the size of the input file stream:
file.seekg(0, std::ios::end);
std::streampos fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// read the file into the string:
std::string fileData(fileSize);
file.read(&fileData[0], fileSize);
"代码行数更少"并不总是意味着"更好"。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL