将整个ASCII文件读入C ++ std :: string [重复]

人盡茶涼 提交于 2020-08-07 09:45:17

问题:

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 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 ...

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? 有任何想法吗?


解决方案:

参考一: https://stackoom.com/question/Autx/将整个ASCII文件读入C-std-string-重复
参考二: https://oldbug.net/q/Autx/Read-whole-ASCII-file-into-C-std-string-duplicate
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!