簡體   English   中英

從C中的二進制文件讀取ith結構

[英]Reading ith structure from a binary file in C

我有一些二進制文件,我將結構對象寫入(一種已定義類型)。 我希望能夠將特定的(ith)“結構塊”從二進制文件讀取到結構中並顯示出來。 我想到的唯一想法是創建包含所有結構的一系列結構,以便我可以訪問普通結構,但這似乎不是一種有效的方法。 如果有人可以幫助我解決這個問題,我將不勝感激:)

我是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 ,文件長度等),並且沒有分離核心概念。

歡迎反饋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM