Hag*_*ble 0 c struct file input
嗨,我必须将结构变量的内容写入文件.我有一个工作程序,但输出看起来扭曲,你可以理解当你看输出.代码的简单版本如下,输出如下.
码:
#include<stdio.h>
#include <stdlib.h>
struct mystruct
{
 char xx[20];
 char yy[20];
 int zz;
};
void filewrite(struct mystruct *myvar)
{
   FILE *f;
   f = fopen("trace.bin","wb");
   if (f == NULL)
   {
     printf("\nUnable to create the file");
     exit(0);
   }
   fwrite(myvar, sizeof(struct mystruct), 1, f);
   fclose(f);
}
void main()
{
    struct mystruct myvar = {"Rambo 1", "Rambo 2", 1234};
    filewrite(&myvar);
}
输出:
(1.整数'1234'在哪里?我需要完整.)
(2.为什么会出现一些随机字符?)
trace.bin
Rambo 1Rambo 2Ò
你的程序是正确的,输出也是......
您正在编写包含内存中原始数据的二进制文件.整数zz以4个字节(或2个,取决于系统中int的大小)写入磁盘,最低有效字节(我猜的是Intel机器).
1234(十进制)被写入0xD2,0x04,0x00,0x00到磁盘.当你以文本形式查看时,0xD2是一个Ò.0x04和0x是不可打印的字符,因此它们不显示.