【问题标题】:Reading ith structure from a binary file in C从C中的二进制文件中读取第i个结构
【发布时间】:2015-05-16 23:05:05
【问题描述】:

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

【问题讨论】:

  • 如果您编写的代码可以成功地将结构写入文件,那么您至少有能力在这方面做出努力。我们不是代码编写服务。
  • 既然你知道每个结构的大小,它应该很容易。
  • 当您编写要发布的示例时,请考虑文件偏移量(ith - 1) * sizeof (struct yourstruct)
  • Carey Gregory:我在哪里要求为我编写代码?我只是要求解释程序。我不知道如何为此目的使用 fread 函数,因为没有指针说明符来引用文件中的特定位置。

标签: c file binary structure


【解决方案1】:

我是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;
}

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

欢迎反馈。

【讨论】:

  • 除了您明确提到的没有错误处理之外,您所拥有的对于具有固定大小且没有指针的简单结构非常有效。如果您必须处理可变大小的结构,或者这些结构包含指针而不是固定大小的数组,生活会变得更加棘手。使用 FAM(灵活数组成员)的结构也存在问题,因为它们也不是固定大小。此类问题可以处理;它需要 很多 更多代码才能做到这一点。
  • 一个值得思考的改变是将声明与初始化结合起来。例如,您可以将:FILE *file_pointer; file_pointer = fopen("filename.dat","rb");(2 个语句)替换为 FILE *file_pointer = fopen("filename.dat","rb");(1 个语句)。这适用于 C89。同样,您可以将struct my_struct this_struct; this_struct.prop1=property; this_struct.prop2=property*2;(3 个语句)替换为struct my_struct this_struct = { property, property*2 };(C89)甚至struct my_struct this_struct = { .prop1 = property, .prop2 = property*2 };(C99 指定的初始值设定项)。
猜你喜欢
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多