【发布时间】:2020-08-19 14:20:13
【问题描述】:
我正在尝试创建一个二进制文件,其中包含在某些struct 中定义的多个二进制记录。但是,我似乎无法找到如何做到这一点。查看其他示例,我已经成功地编写了strings,但不是struct。我只想像在C 和fwrite(3) 中一样编写它,但在D 版本2 中。
这是我迄今为止尝试过的:
- 使用
stream.write(tr)- 编写人类可读/调试表示 - 使用
stream.rawWrite(tr)- 这听起来像我需要的,但无法编译:
错误:模板 std.stdio.File.rawWrite 无法从中推断出函数 参数类型 !()(TitleRecord),候选者是:
/usr/lib/ldc/x86_64-linux-gnu/include/d/std/stdio.d(1132):std.stdio.File.rawWrite(T)(在T[]缓冲区中)
- 如上所述尝试
rawWrite,但将数据转换为各种事物,也永远无法编译。 - 甚至尝试使用
fwrite回到C,但无法深入到获取我需要的文件描述符。
阅读the docs 并没有太大帮助(写字符串对我也有用,但不写struct)。我确定必须有简单的方法来做到这一点,但我找不到它.... 其他 SO 问题did nothelp me。我D 1.0,它可能已经用stream.writeExact(&tr, tr.sizeof) 完成了,但这不再是一个选项。
import std.stdio;
struct TitleRecord {
short id;
char[49] text;
};
TitleRecord tr;
void main()
{
auto stream = File("filename.dat","wb+");
tr.id = 1234;
tr.text = "hello world";
writeln(tr);
//stream.write(tr);
//stream.rawWrite(tr);
//stream.rawWrite(cast(ubyte[52]) tr);
//stream.rawWrite(cast(ubyte[]) tr);
//fwrite(&tr, 4, 1, stream);
}
【问题讨论】: