如何仅使用 std::filebuf 将数据(二进制模式)写入文件



请检查以下代码:

#include <iostream>
#include <string>
#include <fstream>
int main()
{
    char mybuffer[512];
    std::filebuf* optr = new std::filebuf();
    optr->pubsetbuf(mybuffer, 512);
    const char sentence[] = "Sample sentence";
    auto ptr = optr->open("bd.bin", std::ios::binary | std::ios::trunc | std::ios::out);
    if (ptr) {
        float fx = 13;
        auto n = optr->sputn(sentence, sizeof(sentence) - 1);
        n += optr->sputn(reinterpret_cast<const char*>(&fx), sizeof(fx));
        optr->pubsync();
    }
    optr->close();
    if(optr) { delete optr; }
    return 0;
}

运行此程序后,没有数据写入文件,而 sputn -> n 返回有效数量的写入字符(通过调试验证(。

您的代码在我的系统上运行良好,生成一个包含 19 个字符的bd.bin

确定这正是您构建和运行的内容吗?也许您正在使用有问题的编译器,或者磁盘空间不足或其他内容。

使用正确的工具来完成工作。 filebuf只是流式传输到的缓冲区。在iostreams API中编写的实际内容是std::ostream

std::filebuf file;
if (file.open(...)) {
    std::ostream os(&file);
    os << sentence;
    os.write(reinterpret_cast<const char*>(&fx), sizeof(fx));
}

记住使用<<write()也更容易,而不是处理streambuf API的神秘命名functinos的迷宫。

最新更新