为了提高从文件读取的性能,我尝试将大(几个 MB)文件的全部内容读入内存,然后使用 istringstream 访问信息。
我的问题是,读取此信息并将其“导入”到字符串流中的最佳方式是什么?这种方法的一个问题(见下文)是,在创建字符串流时,缓冲区会被复制,内存使用量会增加一倍。
#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
:
#include <fstream>
#include <sstream>
int main()
{
std::ifstream file( "myFile" );
if ( file )
{
std::stringstream buffer;
buffer << file.rdbuf();
file.close();
// operations on the buffer...
}
}
编辑:正如马丁约克在评论中所说,这可能不是自stringstream
's operator<<
将逐个字符读取 filebuf。您可能想检查他的答案,他使用ifstream
's read
像以前一样的方法,然后设置stringstream
buffer 指向先前分配的内存。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)