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

时间:2013-11-08 09:49:36

标签: c++ file-io

我正在尝试将文件内容复制到缓冲区。

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
}

使用rdbuf直接复制崩溃,但在stringstream上复制然后在缓冲区中工作正常。

有人有解释吗?

2 个答案:

答案 0 :(得分:4)

这是因为rdbuf函数实际上并不返回数据,它返回一个流缓冲区实例。输入操作符<<被重载以处理此对象实例,但memcpy不知道如何处理它。

答案 1 :(得分:2)

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

相关问题