我有一个学生的结构,写入一个文件所有我想要的是使用任何方法从文件的值初始化数组,目的是将struct值放入数组以帮助排序过程代码给我打孔任何想法如何实现它
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
struct student
{
char id[5];
char name[30];
int term;
float gpa;
char grade;
};
struct student stu;
typedef struct student stud;
int main ()
{
FILE *fp;
fp = fopen("record.txt","ab+");
char nextChar = getc(fp);
int numCharacters = 0;
while (nextChar != EOF)
{
numCharacters++;
nextChar = getc(fp);
}
//////// detect number of characters ////////
int chunck = numCharacters/sizeof(stu);
stud *arr = (stud *)malloc(chunck);
/*//problem comes next ...
// intial the array of students with records from file
while(fread(&stu,sizeof(stu),1,fp) == 1)
{
for(d=0;d<chunck;d++)
{
arr[d].id=stu.id;
arr[d].name=stu.name;
arr[d].term=stu.term;
arr[d].gpa=stu.gpa;
}
}*/
return 0;
}
答案 0 :(得分:0)
在您阅读和初始化arr struct
之前,需要再次将光标放在文件的开头。
如评论中所述----&gt;使用fseek
或rewind