C++ converting file stream function to use a stringstream
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 istrings开发者_运维百科tream &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?
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);
精彩评论