简体   繁体   中英

fstream to buffer works, filebuf to buffer doesn't

I am trying to convert my code from std::fstream to std::filebuf:

fstream version (the original):

std::ifstream stream(file);
stream.seekg(0,std::ios::end);
size_t fileSize = stream.tellg();
char * dataBuf = new char[fileSize];

stream.seekg(0);
stream.read(dataBuf, fileSize);

LoadData(dataBuf);

filebuf version (the conversion):

std::filebuf * stream = new std::filebuf;
stream->open(file, std::ios::in);
size_t fileSize = stream->pubseekoff(0, std::ios::end);
char * dataBuf = new char[fileSize];

stream->pubseekpos(0);
stream->pubsetbuf(dataBuf, fileSize);
LoadData(dataBuf);

The filebuf version doesn't seem to get loaded. I don't know what I am missing because the fileSize s are the same and the dataBuf s return the same string. Is there any additional function I should perform?

The call to pubsetbuf() is bound not to do you much good. The only required behavior is that stream->pubsetbuf(0, 0) makes the file buffer unbuffered which you almost certainly don't want. It doesn't make any guarantees what happens if the arguments are non-null. In particular, it doesn't guarantee that the buffer being used is the one being passed! In fact, I'd be surprised if any implementation were to use a user provided buffer. Even if the buffer were used, the file buffer would have no reason with the code given to actually put anything into the buffer! At the very least you'd need to cause a call std::filebuf::underflow() , eg, reading something from the buffer.

If you want to use std::filebuf directly you'll need to use std::filebuf::sgetn() . There isn't really much point in doing so as std::ifstream::read() will effectively just call std::filebuf::sgetn() anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM