将整个ASCII文件读入C ++ std :: string

时间:2010-04-08 17:19:49

标签: c++ string caching file-io standard-library

我需要将整个文件读入内存并将其放在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()

有什么想法吗?

9 个答案:

答案 0 :(得分:717)

有几种可能性。我喜欢使用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”)所以你所做的一切保留了一些你从未使用的额外空间。再说一遍,并不是真的会引起重大问题,但无论如何都会感到有点不对劲。

答案 1 :(得分:476)

更新:事实证明,这种方法在遵循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>());

答案 2 :(得分:56)

我认为最好的方法是使用字符串流。简单快捷!!!

#include <fstream>
#include <iostream>
#include <sstream> //std::stringstream
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 << std::endl; //you can do anything with the string!!!
}

答案 3 :(得分:11)

你可能在任何书籍或网站上都找不到这个,但我发现它运作良好:

ifstream ifs ("filename.txt");
string s;
getline (ifs, s, (char) ifs.eof());

答案 4 :(得分:6)

尝试以下两种方法之一:

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
}

答案 5 :(得分:2)

我想出了另一种适用于大多数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();
}
}

答案 6 :(得分:1)

我可以这样做:

void readfile(const std::string &filepath,std::string &buffer){
    std::ifstream fin(filepath.c_str());
    getline(fin, buffer, char(-1));
    fin.close();
}

如果这是令人不悦的事情,请告诉我原因

答案 7 :(得分:1)

如果您碰巧使用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;
}

答案 8 :(得分:-6)

我认为如果没有显式或隐式循环,没有先读入char数组(或其他容器),并且构造字符串,则不能这样做。如果您不需要字符串的其他功能,则可以使用与vector<char>相同的char *方式完成此操作。