为了提高从文件读取数据的性能,我试图将一个大(几MB)文件的全部内容读入内存,然后使用istringstream来访问这些信息。如何将文件内容读入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
*/
}
您喜欢复制数据。 1)复制到缓冲区。 2)复制到匿名的std :: string。 3)复制到iss。 – 2008-09-26 10:34:43
也许你应该搜索内存映射文件。 – 2008-09-25 09:50:28