【问题标题】:Writing the binary file using wfstream使用 wfstream 写入二进制文件
【发布时间】:2016-07-26 05:05:23
【问题描述】:

我想使用wfstram 类在二进制文件中写入结构数据。

为什么输出文件是空的?

以下是我的代码。

#include "stdafx.h"
#include <string>
#include <fstream>

using namespace std;

struct bin_data
{
    wstring ch;
    size_t id;
};

int main()
{

    wfstream   f(L"test_bin_file.txt", ios::out | ios::binary);
    bin_data *d = new bin_data;
    d->id = 100;
    d->ch = L"data100";
    f.write((wchar_t*)&d, sizeof(struct bin_data));
    f.close();

    return 0;
}

【问题讨论】:

  • 如果您希望可以将字符串内容保存到文件中,那您就错了。您将只保存指针/计数器
  • 你不需要&amp;d,这只是废话
  • 那么d怎么写?
  • 先写id,定长,f.write((char*)&amp;d-&gt;id, sizeof(size_t));再写字符串长度,再用d-&gt;ch.data()定字符串的记录和最后内容
  • std::wfstream存在的目的是在程序端以wchar_t表示的Unicode码点与以chars表示的UTF-8、GB18030或其他种类的窄多字节编码之间进行转换, 在文件系统方面。给它一个 ios::binary 并不会改变这一点

标签: c++ binaryfiles


【解决方案1】:

在处理二进制数据时,我不太喜欢使用宽流 - 二进制最终是字节,因此您不必担心 char 与 wchar 的关系。下面的代码在 x64 上写入 30 个字节 - 8 个字节用于 id,8 个字节用于长度,14 (7*2) 个字节用于字符串本身

int main() {
ofstream  f(L"QQQ.txt", ios::out | ios::binary);

bin_data *d = new bin_data;
d->id = 100;
d->ch = L"data100";

// ID first
f.write((char*)&d->id, sizeof(d->id));
// then string length
auto l = d->ch.length();
f.write((char*)&l, sizeof(l));
// string data
f.write((char*)d->ch.data(), l*sizeof(wchar_t));

f.close();

return 0;
}

【讨论】:

    猜你喜欢
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2015-02-22
    • 1970-01-01
    相关资源
    最近更新 更多