从二进制文件中读取随机struct数组元素

时间:2014-04-04 19:54:08

标签: c arrays file struct

我有一个非常大的数组(100k),其中元素随机放置,数组索引作为主键。我试图找出一种方法来使用索引键作为偏移量使用fseek访问数组元素。出于某种原因,无论我给出什么偏移,我都会回来。以下是问题的简单表示。

帮助表示感谢。对不起,如果这是转贴。我无法在任何地方找到类似的问题。

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

 typedef struct student
 {
   char *name;
   int marks;
 }student;

 student class[] = {
   [5]{"Jack",34},
   [12]{"Jane",56},
   [53]{"Joe",72}
 };

 main()
 {
   FILE *f, *f1;
   student rec;

   f = fopen("student.data", "wb");
   fwrite(class, sizeof(student), sizeof(class), f);
   fclose(f);

   if((f1 = fopen("student.data","rb"))==NULL)
   {
     printf("\nError in Opening File\n");
     exit(0);
   }

   /* I want to  seek to 12th element in the array and print 'Jane' */
   fseek(f1, sizeof(student) * 12, SEEK_SET);
   fread(&rec, sizeof(student), 1, f1);

   printf("Name:%s\n", rec.name);

   fclose(f1);
 }

1 个答案:

答案 0 :(得分:0)

你的例子适合我。我唯一需要改变的是使用双引号而不是单引号进行类数组初始化:

cat student.c; gcc student.c; ./a.out

给出以下输出:

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

 typedef struct student
 {
   char *name;
   int marks;
 }student;

 student class[] = {
   [5]{"Jack",34},
   [12]{"Jane",56},
   [53]{"Joe",72}
 };

 main()
 {
   FILE *f, *f1;
   student rec;

   f = fopen("student.data", "wb");
   fwrite(class, sizeof(student), sizeof(class), f);
   fclose(f);

   if((f1 = fopen("student.data","rb"))==NULL)
   {
     printf("\nError in Opening File\n");
     exit(0);
   }

   /* I want to  seek to 12th element in the array and print 'Jane' */
   fseek(f1, sizeof(student) * 12, SEEK_SET);
   fread(&rec, sizeof(student), 1, f1);

   printf("Name:%s\n", rec.name);

   fclose(f1);
 }
Name:Jane