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

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

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

有什么想法吗?


长风秋雁
浏览 700回答 3
3回答

三国纷争

有几种可能性。我喜欢用字符串作为中间的一种:std::ifstream&nbsp;t("file.txt");std::stringstream&nbsp;buffer;buffer&nbsp;<<&nbsp;t.rdbuf();现在,“file.txt”的内容在字符串中可用,如buffer.str().另一种可能性(虽然我也不喜欢)更像是你的原作:std::ifstream&nbsp;t("file.txt");t.seekg(0,&nbsp;std::ios::end);size_t&nbsp;size&nbsp;=&nbsp;t.tellg();std::string&nbsp;buffer(size,&nbsp;'&nbsp;');t.seekg(0);t.read(&buffer[0],&nbsp;size);在官方上,这不需要在C+98或03标准下工作(字符串不需要连续存储数据),但实际上它可以与所有已知的实现一起工作,而且C+11和更高版本确实需要连续存储,因此可以保证与它们一起工作。至于为什么我也不喜欢后者:第一,因为它更长,更难读。第二,因为它要求您用您不关心的数据初始化字符串的内容,然后立即对该数据进行写入(是的,与读取相比,初始化的时间通常是微不足道的,所以这可能并不重要,但对我来说,这仍然是错误的)。第三,在文本文件中,X在文件中的位置不一定意味着你必须读取X字符才能达到这个值-它不需要考虑像行尾翻译之类的内容。在执行此类转换(例如,Windows)的实际系统中,翻译后的表单比文件中的内容短(即文件中的“\r\n”在已翻译的字符串中变为“\n”),因此您所做的只是保留了一些您从未使用过的额外空间。再说一遍,这并不是真正的大问题,但还是觉得有点不对劲。

慕盖茨4494581

我认为最好的方法是使用字符串流。简单又快!#include&nbsp;<fstream>#include&nbsp;<iostream>#include&nbsp;<sstream>&nbsp;//std::stringstreammain(){ &nbsp;&nbsp;&nbsp;&nbsp;std::ifstream&nbsp;inFile; &nbsp;&nbsp;&nbsp;&nbsp;inFile.open("inFileName");&nbsp;//open&nbsp;the&nbsp;input&nbsp;file &nbsp;&nbsp;&nbsp;&nbsp;std::stringstream&nbsp;strStream; &nbsp;&nbsp;&nbsp;&nbsp;strStream&nbsp;<<&nbsp;inFile.rdbuf();&nbsp;//read&nbsp;the&nbsp;file &nbsp;&nbsp;&nbsp;&nbsp;std::string&nbsp;str&nbsp;=&nbsp;strStream.str();&nbsp;//str&nbsp;holds&nbsp;the&nbsp;content&nbsp;of&nbsp;the&nbsp;file &nbsp;&nbsp;&nbsp;&nbsp;std::cout&nbsp;<<&nbsp;str&nbsp;<<&nbsp;std::endl;&nbsp;//you&nbsp;can&nbsp;do&nbsp;anything&nbsp;with&nbsp;the&nbsp;string!!!}
打开App,查看更多内容
随时随地看视频慕课网APP