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