本文共 4447 字,大约阅读时间需要 14 分钟。
本文翻译自:
This question already has an answer here: 这个问题已经在这里有了答案:
I need to read a whole file into memory and place it in a C++ std::string
. 我需要将整个文件读入内存并将其放在C ++ std::string
。
If I were to read it into a char[]
, the answer would be very simple: 如果我将其读入char[]
,答案将非常简单:
std::ifstream t;int length;t.open("file.txt"); // open input filet.seekg(0, std::ios::end); // go to the endlength = t.tellg(); // report location (this is the length)t.seekg(0, std::ios::beg); // go back to the beginningbuffer = new char[length]; // allocate memory for a buffer of appropriate dimensiont.read(buffer, length); // read the whole file into the buffert.close(); // close file handle// ... Do stuff with buffer here ...
Now, I want to do the exact same thing, but using a std::string
instead of a char[]
. 现在,我想做完全相同的事情,但是使用std::string
而不是char[]
。 I want to avoid loops, ie 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()
Any ideas? 有任何想法吗?
参考:
I could do it like this: 我可以这样做:
void readfile(const std::string &filepath,std::string &buffer){ std::ifstream fin(filepath.c_str()); getline(fin, buffer, char(-1)); fin.close();}
If this is something to be frowned upon, please let me know why 如果您对此不满意,请告诉我为什么
I think best way is to use string stream. 我认为最好的方法是使用字符串流。 simple and quick !!! 简单快捷!
#include#include #include //std::stringstreamint main() { std::ifstream inFile; inFile.open("inFileName"); //open the input file std::stringstream strStream; strStream << inFile.rdbuf(); //read the file std::string str = strStream.str(); //str holds the content of the file std::cout << str << "\n"; //you can do anything with the string!!!}
I figured out another way that works with most istreams, including std::cin! 我想出了适用于大多数istream的另一种方法,包括std :: cin!
std::string readFile(){ stringstream str; ifstream stream("Hello_World.txt"); if(stream.is_open()) { while(stream.peek() != EOF) { str << (char) stream.get(); } stream.close(); return str.str(); }}
Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! 更新:事实证明,这种方法虽然很好地遵循了STL习惯用法,但实际上效率低得多! Don't do this with large files. 不要对大文件执行此操作。 (See: ) (请参阅: : )
You can make a streambuf iterator out of the file and initialize the string with it: 您可以从文件中制作一个streambuf迭代器,并使用它初始化字符串:
#include#include #include std::ifstream t("file.txt");std::string str((std::istreambuf_iterator (t)), std::istreambuf_iterator ());
Not sure where you're getting the t.open("file.txt", "r")
syntax from. 不知道从哪里获取t.open("file.txt", "r")
语法。 As far as I know that's not a method that std::ifstream
has. 据我所知,这不是std::ifstream
具有的方法。 It looks like you've confused it with C's fopen
. 您似乎已经将其与C的fopen
混淆了。
Edit: Also note the extra parentheses around the first argument to the string constructor. 编辑:还请注意字符串构造函数的第一个参数周围的多余括号。 These are essential . 这些是必不可少的 。 They prevent the problem known as the " ", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results. 它们可以防止称为“ ”的问题,在这种情况下,它实际上不会像通常那样给您带来编译错误,但会给您带来有趣的(错误的)结果。
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): 遵循KeithB在评论中的观点,这是一种预先分配所有内存的方法(而不是依赖于字符串类的自动重新分配):
#include#include #include 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 (t)), std::istreambuf_iterator ());
I don't think you can do this without an explicit or implicit loop, without reading into a char array (or some other container) first and ten constructing the string. 我认为如果没有显式或隐式循环,而没有先读入char数组(或其他容器),又没有十个构造字符串的方法,您将无法做到这一点。 If you don't need the other capabilities of a string, it could be done with vector<char>
the same way you are currently using a char *
. 如果不需要字符串的其他功能,则可以使用vector<char>
来完成,就像您当前使用char *
。
转载地址:http://nicnb.baihongyu.com/