从C

时间:2015-05-16 23:05:06

标签: c file binary structure

我有一些二进制文件,我将struct对象写入(一个已定义的类型)。我希望能够从二进制文件中读取特定的(ith)“struct block”到结构并显示它。我想到的唯一想法是创建一个包含所有这些结构的结构数组,以便我可以访问普通的结构,但它似乎不是一种有效的方式。 如果有人可以帮我解决这个问题,我将不胜感激:)

1 个答案:

答案 0 :(得分:3)

new to C但我想我可以帮忙解决这个问题。这是你想要做的事情:

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

//just a struct for purposes of demonstration
struct my_struct{
  int prop1;
  int prop2;
};

//writes structs to filename.dat
void writeStruct(int property){
  FILE *file_pointer;
  file_pointer = fopen("filename.dat","ab");

  //define and assign variables to a quick dummy struct
  struct my_struct this_struct;
  this_struct.prop1=property;
  this_struct.prop2=property*2;

  //write struct to file
  fwrite(&this_struct, sizeof(this_struct), 1, file_pointer);
  fclose(file_pointer);
}

//returns the nth struct stored in "filename.dat"
struct my_struct getNthStruct(long int n){
  FILE *file_pointer;
  file_pointer = fopen("filename.dat","rb");

  //will be the struct we retrieve from the file
  struct my_struct nth_struct;

  //set read position of file to nth struct instance in file
  fseek(file_pointer, n*sizeof(struct my_struct), SEEK_SET);

  //copy specified struct instance to the 'nth_struct' variable
  fread(&nth_struct, sizeof(struct my_struct), 1, file_pointer);

  return nth_struct;
}

int main(){
  //write a bunch of structs to a file
  writeStruct(1);
  writeStruct(2);
  writeStruct(3);
  writeStruct(4);
  writeStruct(5);

  //get nth struct (2 is third struct, in this case)
  struct my_struct nth_struct;
  nth_struct=getNthStruct(2);

  printf("nth_struct.prop1=%d, nth_struct.prop2=%d\n",
      nth_struct.prop1, //outputs 3
      nth_struct.prop2); //outputs 6

  return 0;
}

我故意没有检查明显的错误(FILE指针返回NULL,文件长度等)以简洁和隔离核心概念。

欢迎提供反馈。