这个问题在这里已有答案:
我需要将整个文件读入内存并将其放在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()
有任何想法吗?
更新:事实证明,这种方法,虽然很好地遵循STL习语,实际上效率低得惊人!不要对大文件这样做。 (见:http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html)
你可以从文件中创建一个streambuf迭代器并用它初始化字符串:
#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
搞混了。
编辑:还要注意字符串构造函数的第一个参数周围的额外括号。这些都很重要。它们可以防止称为“most vexing parse”的问题,在这种情况下,它实际上不会像通常那样给你一个编译错误,但会给你带来有趣的(读取:错误的)结果。
遵循KeithB在评论中的观点,这里有一种方法可以预先分配所有内存(而不是依赖于字符串类的自动重新分配):
#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>());
有几种可能性。我喜欢使用stringstream作为中间人:
std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
现在,“file.txt”的内容以buffer.str()
的字符串形式提供。
另一种可能性(虽然我当然也不喜欢它)更像你的原创:
std::ifstream t("file.txt");
t.seekg(0, std::ios::end);
size_t size = t.tellg();
std::string buffer(size, ' ');
t.seekg(0);
t.read(&buffer[0], size);
正式地说,这不需要在C ++ 98或03标准下工作(字符串不需要连续存储数据)但事实上它适用于所有已知的实现,而C ++ 11及更高版本确实需要连续的存储,所以它保证与他们合作。
至于为什么我不喜欢后者:首先,因为它更长,更难阅读。其次,因为它需要用你不关心的数据初始化字符串的内容,然后立即写入数据(是的,初始化的时间通常与读数相比是微不足道的,所以它可能无关紧要,但对我来说,它仍然感觉有点不对劲)。第三,在文本文件中,文件中的位置X并不一定意味着您将读取X字符以达到该点 - 不需要考虑线端翻译之类的内容。在进行此类翻译的真实系统(例如,Windows)上,翻译后的表单比文件中的内容短(即,文件中的“\ r \ n”在翻译后的字符串中变为“\ n”)所以你所做的一切保留了一些你从未使用的额外空间。再说一遍,并不是真的会造成重大问题,但无论如何都会感到有点不对劲。
我认为最好的方法是使用字符串流。简单快捷!!!
#include <fstream>
#include <iostream>
#include <sstream> //std::stringstream
int 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!!!
}
你可能在任何书籍或网站上都找不到这个,但我发现它运作得很好:
ifstream ifs ("filename.txt");
string s;
getline (ifs, s, (char) ifs.eof());
尝试以下两种方法之一:
string get_file_string(){
std::ifstream ifs("path_to_file");
return string((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
}
string get_file_string2(){
ifstream inFile;
inFile.open("path_to_file");//open the input file
stringstream strStream;
strStream << inFile.rdbuf();//read the file
return strStream.str();//str holds the content of the file
}
我想出了另一种适用于大多数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();
}
}
如果您碰巧使用glibmm,您可以尝试Glib::file_get_contents。
#include <iostream>
#include <glibmm.h>
int main() {
auto filename = "my-file.txt";
try {
std::string contents = Glib::file_get_contents(filename);
std::cout << "File data:\n" << contents << std::endl;
catch (const Glib::FileError& e) {
std::cout << "Oops, an error occurred:\n" << e.what() << std::endl;
}
return 0;
}
我可以这样做:
void readfile(const std::string &filepath,std::string &buffer){
std::ifstream fin(filepath.c_str());
getline(fin, buffer, char(-1));
fin.close();
}
如果这是令人不悦的事情,请告诉我原因
我不认为你可以在没有显式或隐式循环的情况下执行此操作,而不首先读取char数组(或其他容器),然后构造字符串。如果你不需要字符串的其他功能,可以使用vector<char>
以与当前使用char *
相同的方式完成。