【问题标题】:How to write data(binary mode) in to a file only using std::filebuf?如何仅使用 std::filebuf 将数据(二进制模式)写入文件?
【发布时间】:2018-03-06 19:42:18
【问题描述】:

请检查以下代码:

#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 正在返回有效的写入字符数(通过调试验证)。

【问题讨论】:

    标签: c++ filebuf


    【解决方案1】:

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

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

    【讨论】:

    • 我用的是VS2017最新的编译器:(
    • @BuddhikaChaturanga:我的意思是,您的代码是有效的。问题出在其他地方。
    【解决方案2】:

    为工作使用正确的工具。 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));
    }
    

    记住使用&lt;&lt;write() 也比处理streambuf API 的神秘命名函数迷宫更容易。

    【讨论】:

    • ... 但这也不是 OP 工作的编写工具,因为他/她可能希望能够说 something &lt;&lt; fx 并获得与您的 os.write() 完全相同的效果,即按原样将八位字节从内存中复制到文件中。
    • @einpoklum 好吧,如果你想写的话……os &lt;&lt; as_bytes(fx);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多