C++使用 ofstream 写入二进制文件
对于我正在开发的小文件格式,我需要将 519 字节的标头输出到文件中。我对整个 ofstream 概念有点陌生。尽管我在阅读 Truevision Targa 文件的标头方面有一些经验。但输出是我非常熟悉的东西。
基本上,这是我的问题。
我打开了一个 ofstream 实例,我需要输出一个像这样的标头:
typedef struct header {
char version; // offset 0, length 1
short int width; // offset 1, length 2
short int height; // offset 3, length 2
short int pathlen; // offset 5, length 2
char desc[512]; // offset 7, length 512
} fileHeader;
现在我需要在文件的前 519 个字节中获取所有这些内容,其余内容各不相同,我将如何将此标头复制到我的文件?
我最好使用 ofstream 类来完成此操作,但我也可以使用原始的 C 库。我已经花了两个小时了,但还没有取得任何进展,尝试在谷歌上搜索也没有多大帮助。
For a small file format I'm developing I need to output a header of 519 bytes to a file. I'm a bit new to the whole ofstream concept. Though I have some experience with reading the header of a Truevision Targa file. But output is something I'm far lees familiar with.
So basically, here is my problem.
I opened an instance of ofstream, and I need to output a header like so:
typedef struct header {
char version; // offset 0, length 1
short int width; // offset 1, length 2
short int height; // offset 3, length 2
short int pathlen; // offset 5, length 2
char desc[512]; // offset 7, length 512
} fileHeader;
Now I need to get all of this in the first 519 bytes of a file, the rest of the content varies, how would I go around copying this header into my file?
I preferably want to do this using the ofstream class, but I'm also fine with the original C library. I've been at this for 2 hours now, and I've not gotten anywhere yet and trying to search on Google doesn't help much either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您没有指针,所以这相当简单! (请注意,这只适用于窄流)
另一个用文本和动态内存/指针/等显示内容的示例
Since you have no pointers, it's fairly easy! (Note this only works with narrow streams)
Another example to show things with text, and dynamic memory/pointers/etc