简体   繁体   English

使用rdbuf将文件内容复制到缓冲区失败

[英]copy file content to a buffer using rdbuf failed

I'm trying to copy file content to a buffer. 我正在尝试将文件内容复制到缓冲区。

std::ifstream fp(myFile, std::ios::binary)
fp.seekg(0, fp.end); // set cursor at the end
int length = fp.tellg(); // get data size
fp.seekg(0, fp.beg); // go back to buffer begin

char data[1000];
if(length<1000) {
    memcpy(data, fp.rdbuf(), length); // This crash

    std::stringstream contents;
    contents << fp.rdbuf();
    memcpy(data, contents->str().c_str(), length); // works fine
}

Copy using rdbuf directly crash, but copy on stringstream then in buffer works fine. 使用rdbuf的复制直接崩溃,但是在stringstream上复制然后在缓冲区中可以正常工作。

Does anybody has an explanation ? 有人有解释吗?

It's because the rdbuf function doesn't actually return the data, it returns a stream buffer instance. 这是因为rdbuf函数实际上并不返回数据,而是返回一个流缓冲区实例。 The input operator << is overloaded to handle this object instance, but memcpy don't know what do do with it. 输入运算符<<重载以处理此对象实例,但是memcpy不知道如何处理它。

rdbuf()不返回可以使用memcpy的缓冲区,它返回一个streambuf对象。

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

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