简体   繁体   English

fstream缓冲工作,filebuf缓冲不

[英]fstream to buffer works, filebuf to buffer doesn't

I am trying to convert my code from std::fstream to std::filebuf: 我正在尝试将我的代码从std :: fstream转换为std :: filebuf:

fstream version (the original): fstream版本(原始):

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): filebuf版本(转换):

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. filebuf版本似乎未加载。 I don't know what I am missing because the fileSize s are the same and the dataBuf s return the same string. 我不知道缺少什么,因为fileSize相同,而dataBuf返回相同的字符串。 Is there any additional function I should perform? 我应该执行其他功能吗?

The call to pubsetbuf() is bound not to do you much good. 调用pubsetbuf()肯定不会对您有多大帮助。 The only required behavior is that stream->pubsetbuf(0, 0) makes the file buffer unbuffered which you almost certainly don't want. 唯一需要的行为是stream->pubsetbuf(0, 0)使文件缓冲区成为没有缓冲的,而您几乎肯定不希望这样做。 It doesn't make any guarantees what happens if the arguments are non-null. 它不能保证如果参数为非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. 至少您需要引起一个std::filebuf::underflow()调用,例如,从缓冲区中读取内容。

If you want to use std::filebuf directly you'll need to use std::filebuf::sgetn() . 如果要直接使用std::filebuf需要使用std::filebuf::sgetn() There isn't really much point in doing so as std::ifstream::read() will effectively just call std::filebuf::sgetn() anyway. 这样做并没有多大意义,因为std::ifstream::read()只会有效地调用std::filebuf::sgetn()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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