gpt4 book ai didi

c - 从二进制文件中读取随机结构数组元素

转载 作者:行者123 更新时间:2023-11-30 17:35:51 25 4
gpt4 key购买 nike

我有一个非常大的数组(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);
}

最佳答案

你的例子对我有用。我唯一需要更改的是在类数组初始化中使用双引号而不是单引号:

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

关于c - 从二进制文件中读取随机结构数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22871890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com