【发布时间】:2011-02-05 19:37:54
【问题描述】:
我需要将整个文件读入内存并将其放入 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()
有什么想法吗?
【问题讨论】:
-
总会涉及到一个循环,但它可以作为标准库的一部分隐含。这可以接受吗?你为什么要避免循环?
-
我相信发帖者知道读取字节涉及循环。他只是想要一个简单的、perl 风格的 gulp 等价物。这涉及编写少量代码。
-
如果 std::string 不为其字符串数据使用连续缓冲区(这是允许的),此代码有问题:stackoverflow.com/a/1043318/1602642
-
@ChrisDesjardins:(1) 您的链接已过时(C++11 使其连续)并且 (2) 即使不是,
std::getline(istream&, std::string&)仍然会做正确的事情。跨度> -
查看此代码的任何人的旁注:作为读取 char[] 示例的代码不会以空值终止数组(读取不会自动执行此操作),这可能不是你期待。
标签: c++ string caching file-io standard-library