5

I have loads of c++ classes that reads data from a file stream. The functions looks like this.

bool LoadFromFile(class ifstream &file);

I'm creating a new function to read from memory instead of a file. So I googled around and a istringstream seems to do the trick without any modifications to the code.

bool LoadFromData(class istringstream &file);

Now my question is. I need to construct this stream to read from a char array. The string is not null-terminated, it's pure binary data and I got a integer with the size. I tried assigning it to a string and creating a stream from a string, however the string terminates after a null character.. and the data is copied.

int size;
char *data;
string s = *data;

How do I create a string from a char array pointer without copying the data + specifying the size of the pointer data? Do you know any other solution than a stringstream?

Tito
  • 71
  • 1
  • 4
  • 1
    So, clarification: Is your problem that your `char *` is not null terminated and therefore you're having trouble constructing an `std::string` out of it? – flight Sep 20 '11 at 11:14
  • Yea that's the problem basically. I'm also wondering if anyone knows a better solution. – Tito Sep 20 '11 at 11:16
  • Here is maybe the solution: http://stackoverflow.com/questions/2079912/simpler-way-to-create-a-c-memorystream-from-char-size-t-without-copying-th (one version uses boost, on copies the data and one only works with gcc) – Alexander Sulfrian Sep 20 '11 at 11:23

1 Answers1

4

Write an own basic_streambuf class! More details.. (This way you could work on the current memory.)

To create string from pointer and size: string str(data,data+size); (it will copy the data).

On more thing: you should rewrite your functions to based on istream:

bool LoadFromStream(istream &is);

In this way you could do the followings, because both istringstream and ifstream based on istream (later this function could also supports tcp streams...):

ifstream file;
istringstream sstream;

LoadFromStream(file);
LoadFromStream(sstream);
Naszta
  • 7,560
  • 2
  • 33
  • 49
  • Thank you very much! This solved my problem without changing the functions at all! – Tito Sep 20 '11 at 11:37
  • Seems like it worked for the file streams but when I passed a string stream to it I got this compiler error (with the exact code above). I did my best to research it but I just don't get it. It's compiled in VS. cannot convert parameter 1 from 'class std::basic_istringstream,class std::allocator >' to 'class istream &' – Tito Sep 20 '11 at 13:58
  • I use it in many places. You should define as `bool LoadFromStream(istream &is);` against `bool LoadFromStream(class istream &is);` In header file I usually not use `using namespace std;` so the definition is: `bool LoadFromStream(std::istream &is);`. You should include ``. – Naszta Sep 20 '11 at 14:16