将整个 ASCII 文件读入 C++ std::string [英] Read whole ASCII file into C++ std::string

查看:41
本文介绍了将整个 ASCII 文件读入 C++ std::string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to read a whole file into memory and place it in a C++ std::string.

如果我将其读入 char[],答案将非常简单:

If I were to read it into a char[], the answer would be very simple:

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[].我想避免循环,即我不想:

Now, I want to do the exact same thing, but using a std::string instead of a char[]. I want to avoid loops, i.e. I don't want to:

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()

有什么想法吗?

推荐答案

更新: 事实证明,这种方法虽然很好地遵循了 STL 习语,但实际上效率低得惊人!不要对大文件执行此操作.(参见:http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html)

Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html)

您可以从文件中创建一个流缓冲迭代器并用它初始化字符串:

You can make a streambuf iterator out of the file and initialize the string with it:

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
                 std::istreambuf_iterator<char>());

不确定您从哪里获得 t.open("file.txt", "r") 语法.据我所知,这不是 std::ifstream 拥有的方法.看起来您已经将它与 C 的 fopen 混淆了.

Not sure where you're getting the t.open("file.txt", "r") syntax from. As far as I know that's not a method that std::ifstream has. It looks like you've confused it with C's fopen.

还要注意字符串构造函数的第一个参数周围的额外括号.这些是必不可少的.它们防止了称为最烦人的解析",在这种情况下,它实际上不会像通常那样给你一个编译错误,但会给你有趣的(阅读:错误的)结果.

Also note the extra parentheses around the first argument to the string constructor. These are essential. They prevent the problem known as the "most vexing parse", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results.

按照 KeithB 在评论中的观点,这里有一种方法可以预先分配所有内存(而不是依赖字符串类的自动重新分配):

Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation):

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str;

t.seekg(0, std::ios::end);   
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);

str.assign((std::istreambuf_iterator<char>(t)),
            std::istreambuf_iterator<char>());

这篇关于将整个 ASCII 文件读入 C++ std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆