爲了提高從文件讀取數據的性能,我試圖將一個大(幾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