如何读取文件内容到istringstream? [英] How to read file content into istringstream?
问题描述
为了提高从文件读取性能,我试图读取一个大(几MB)文件的整个内容到内存,然后使用istringstream访问信息。
In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information.
我的问题是,这是阅读这些信息和导入到字符串流的最佳方式?这种方法的一个问题(见下面)是,当创建字符串流时,缓冲区被复制,内存使用加倍。
My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (see bellow) is that when creating the string stream the buffers gets copied, and memory usage doubles.
#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()
a filebuf
。然后,您可以将 filebuf
推送到您的 stringstream
:
std::ifstream
has a method rdbuf()
, that returns a pointer to a filebuf
. You can then "push" this filebuf
into your stringstream
:
int main()
{
std::ifstream file( "myFile" );
if ( file )
{
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
// operations on the buffer...
}
}
b $ b
编辑:正如Martin York在评论中所说,这可能不是最快的解决方案,因为 stringstream
的运算符< ;
将逐个字符读取filebuf。你可能想要检查他的答案,在那里他使用 ifstream 的
读
方法,像以前一样,然后将 stringstream
缓冲区设置为指向先前分配的内存。
As Martin York remarks in the comments, this might not be the fastest solution since the stringstream
's operator<<
will read the filebuf character by character. You might want to check his answer, where he uses the ifstream
's read
method as you used to do, and then set the stringstream
buffer to point to the previously allocated memory.
这篇关于如何读取文件内容到istringstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!