读取bin文件,并且按结构体赋值打印

目标:读取一个bin文件,并且将bin文件中的数据,按字节对齐赋值给结构体,并且打印出结构体的内容

目前思路是简单的先将bin文件数据一次性读到一个数组中,再将数组强制转换为结构体

    char buff[256]
    FILE *fp;
    fp = NULL;
    fp = fopen(argv[1], "rb");
    if (NULL == fp)
    {
        printf( "The file was not opened\n");
        return;
    }
    fread(buff, 1, 256, fp);
    struct A a = (struct A) buff; 

另外,在博客看到一个输出结构体的demo,贴在这里

只需要传入要打印结构体的结构体指针和结构体大小,就可以进行打印,且可以控制一行打印的字节数和字节与字节之间是否需要留一个空格

void print_struct_content(void *strp, size_t size)
{
    size_t i;
    char *printbit = (char *)strp;
    int format = 0;
    for (i = 0; i < size; i++)
    {
        printf("%02x", printbit[i]&0XFF);
        format++;
        if (0 == (format % 4))
        {
            printf("\n");
        }
    }
}

参考:

https://blog.csdn.net/XIAXIA__/article/details/9360149

猜你喜欢

转载自www.cnblogs.com/zzdbullet/p/10059397.html