I need to 开发者_开发技巧stream data to a stringstream from a binary file:
stringstream body;
body << std::ifstream( path.string().c_str(), ios::binary).rdbuf();
But it read the whole file from its begining to its end.
How do I read the file to the stringstream starting from 200th
byte, and going to 3000th
?
There's no way that I know of to directly read from the file's read buffer into the stringstream
. That doesn't mean one doesn't exist; it just means that I don't know it off the top of my head. :-)
One option you might want to explore would be to read the data into a temporary buffer, then put that string
into the stringstream
by using the str()
method. This might look as follows:
ifstream input(/* ... filename ... */, ios::binary)
input.seekg(streampos(200)); // Seek to the desired offset.
char buffer[3000 - 200]; // Set up a buffer to hold the result.
input.read(buffer, streamsize(sizeof(buffer)));
stringstream myStream(buffer); // Convert to a stringstream
Hope this helps!
The original answer makes me think that my way of doing this is wrong (and possibly inefficient). However I had managed to do the following to avoid storing the file in a buffer and copying the buffer over to stringstream
(thus creating two copies of the data). The original answer also did not work for me for some reason, so I was forced to find another way.
// This is the size of the data you want to copy
int dataSz = 3000 - 200;
// The input file you are reading from
ifstream infile("filepath.dat", ios::binary);
// The stringstream you want to store part of the file in
stringstream partFileData;
// Seek to the place you want to start reading
infile.seekg(200);
// Loop through the data, reading from the file and writing it
// directly to the stringstream
for (int i = 0; i < dataSz; i++)
{
// temporarily store byte
char byte;
// read one byte
infile.read(&byte, 1);
// write it to stringstream
partFileData.write(&byte, 1);
}
Obviously, you would have to adjust it for your own needs, but the way you would do it is the same.
I am sorry for the very late response, and I am sorry if my code sucks, but I had had this issue and I thought this might help others who had the issue too.
精彩评论