首页 > 解决方案 > 将位转换为人类可读的格式

问题描述

我想将二进制文件读入结构

struct rec
{
    int type;
    long length;
    int data[100];
};

二进制文件的前 16 位是类型,接下来的 32 位是数据的长度,接下来是数据。文件中有多条记录,最后一条记录的长度为 0,表示文件结束。

我想读取并打印每条记录的值。

我想出了一种读取类型和长度的方法,但是在尝试使用长度来读取数据时我被卡住了。另外,我怎样才能把它放在一个循环中直到长度 = 0?

int main()
{
    FILE *ptr_tofile;
    struct rec some_record;
    ptr_tofile=fopen("Test.bin","rb");

    if (!ptr_tofile)
    {
        printf("Unable to open file!");
        return 1;
    }

    for ( until length = 0)
    {
        fread(&some_record, sizeof(int), 1, ptr_tofile);
        printf("%d\n",some_record.type);
        fread(&some_record, sizeof(int), 2, ptr_tofile);
        printf("%d\n",some_record.type);
        getch();
    }
    fclose(ptr_tofile);
    return 0;
}

标签: cfilepointersstructbinary

解决方案


这是使用灵活数组成员的另一种方法:

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

typedef struct file_s {
  int16_t type;
  int32_t length;
  // Assumption: Each record is 16 bits
  // For a record size of 32 bits, use int32_t*
  int16_t* data;
} file_s;

int main() {
  file_s file;
  FILE* f = fopen("file.bin","r");
  if (f == NULL) {
    perror("Error");
    return 1;
  }
  fread(&file.type, sizeof(file.type), 1, f);
  fread(&file.length, sizeof(file.length), 1, f);
  // Assumption: the length of the data is the number of records
  // If the length is in bytes, you should divide it by the size
  // of a record to obtain the number of records
  file.data = malloc(file.length * sizeof(*file.data));
  // sizeof is a compile-time operator so sizeof(*p) is not a null dereference
  fread(file.data, sizeof(*file.data), file.length, f);
  fclose(f);
  // Process the data
  /* ... */
  free(file.data);
  return 0;
}

关于长度表示的内容和记录的大小有一些假设,但您可以对其进行调整以适应您的问题的具体情况。


推荐阅读