如何将文件内容读入istringstream?

为了提高从文件读取性能,我试图将一个大(几MB)文件的全部内容读入内存,然后使用istringstream来访问这些信息。

我的问题是,读取这些信息并将其“导入”stringstream的最佳方法是? 这种方法(见下文)的一个问题是,当创buildstringstream时,缓冲区被复制,内存使用量加倍。

#include <fstream> #include <sstream> using namespace std; int main() { ifstream is; is.open (sFilename.c_str(), ios::binary ); // get length of file: is.seekg (0, std::ios::end); long length = is.tellg(); is.seekg (0, std::ios::beg); // allocate memory: char *buffer = new char [length]; // read data as a block: is.read (buffer,length); // create string stream of memory contents // NOTE: this ends up copying the buffer!!! istringstream iss( string( buffer ) ); // delete temporary buffer delete [] buffer; // close filestream is.close(); /* ================================== * Use iss to access data */ } 

std::ifstream有一个方法rdbuf() ,它返回一个指向filebuf的指针。 然后你可以把这个filebuf “推”到你的stringstream

 int main() { std::ifstream file( "myFile" ); if ( file ) { std::stringstream buffer; buffer << file.rdbuf(); file.close(); // operations on the buffer... } } 

编辑:正如马丁·约克在评论中所言,这可能不是最快的解决scheme,因为stringstreamoperator<<将逐字符读取filebuf字符。 您可能需要检查他的答案,他像以前一样使用ifstreamread方法,然后将stringstream缓冲区设置为指向先前分配的内存。

好。 我不是说这比从文件中读取更快

但是,这是一种创build缓冲区的方法,在将数据读入缓冲区之后,直接将其用作stringstream的源。

NB值得一提的是std :: ifstream被缓冲。 它从相对较大的块中读取文件中的数据。 stream操作是针对缓冲区执行的,只有在需要更多数据时才返回到文件进行另一次读取。 因此,在将所有数据吸入内存之前,请确认这是一个瓶颈。

 #include <fstream> #include <sstream> #include <vector> int main() { std::ifstream file("Plop"); if (file) { /* * Get the size of the file */ file.seekg(0,std::ios::end); std::streampos length = file.tellg(); file.seekg(0,std::ios::beg); /* * Use a vector as the buffer. * It is exception safe and will be tidied up correctly. * This constructor creates a buffer of the correct length. * * Then read the whole file into the buffer. */ std::vector<char> buffer(length); file.read(&buffer[0],length); /* * Create your string stream. * Get the stringbuffer from the stream and set the vector as it source. */ std::stringstream localStream; localStream.rdbuf()->pubsetbuf(&buffer[0],length); /* * Note the buffer is NOT copied, if it goes out of scope * the stream will be reading from released memory. */ } } 

这对我来说似乎是不成熟的优化。 在处理中做了多less工作。 假设一个现代化的桌面/服务器,而不是一个embedded式系统,在初始化过程中复制几MB的数据是相当便宜的,尤其是与从磁盘读取文件相比,首先。 我会坚持你所拥有的,当它完成时衡量系统,并决定潜在的性能收益是否值得。 当然,如果内存紧张,这是一个内部循环,或者经常被调用的程序(如每秒一次),这会改变平衡。

另外要记住的是文件I / O总是最慢的操作。 卢克Touraille的解决scheme是正确的,但也有其他的select。 将整个文件一次读入内存将比单独读取快得多。