相关疑难解决方法(0)

如何将文件内容读入istringstream?

为了提高从文件读取的性能,我试图将大(几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 …
Run Code Online (Sandbox Code Playgroud)

c++ memory optimization stream stringstream

37
推荐指数
2
解决办法
9万
查看次数

无法读取整个文件

我正在制作一个C++程序,以便能够打开.bmp图像,然后将其放入2D数组中.现在我有这样的代码:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "Image.h"
using namespace std;

struct colour{
    int red;
    int green;
    int blue;
};

Image::Image(string location){

    fstream stream;
    string tempStr;

    stringstream strstr;
    stream.open(location);

    string completeStr;

    while(!stream.eof()){
        getline(stream, tempStr);
        completeStr.append(tempStr);
    }
    cout << endl << completeStr;

    Image::length = completeStr[0x13]*256 + completeStr[0x12];
    Image::width = completeStr[0x17]*256 + completeStr[0x16];
    cout << Image::length;
    cout << Image::width;
    cout << completeStr.length();

    int hexInt;
    int x = 0x36;
    while(x < completeStr.length()){
        strstr << noskipws << completeStr[x];
        cout << x …
Run Code Online (Sandbox Code Playgroud)

c++ fstream iostream file bmp

1
推荐指数
1
解决办法
3142
查看次数

标签 统计

c++ ×2

bmp ×1

file ×1

fstream ×1

iostream ×1

memory ×1

optimization ×1

stream ×1

stringstream ×1