【发布时间】:2018-09-05 16:59:37
【问题描述】:
我想学习如何从 文本文件 中加载多个结构(许多学生:姓名、姓氏、索引、地址...),如下所示:
Achilles, 9999
Hector, 9998
Menelaos, 9997
... and so on
结构可以是:
struct student_t {
char *name;
int index;
}
我的尝试(不起作用;我什至不确定 fgets+sscanf 是否是一个相当大的选择):
int numStudents=3; //to simplify... I'd need a function to count num of lines, I imagine
int x, y=1000, err_code=1;
FILE *pfile = fopen("file.txt", "r");
if(pfile==0) {return 2;}
STUDENT* students = malloc(numStudents * sizeof *students);
char buffer[1024];
char *ptr[numStudents];
for (x = 0; x < numStudents; x++){ //loop for each student
students[x].name=malloc(100); //allocation of each *name field
fgets(buffer, 100, pfile); //reads 1 line containing data of 1 student, to buffer
if(x==0) *ptr[x] = strtok(buffer, ",");//cuts buffer into tokens: ptr[x] for *name
else *ptr[x] = strtok(NULL, ","); //cuts next part of buffer
sscanf(ptr[x], "%19s", students[x].name); //loads the token to struct field
*ptr[y] = strtok(NULL, ","); //cuts next part of the buffer
students[y].index = (int)strtol(ptr[y], NULL, 10); //loads int token to struct field
*buffer='\0';//resets buffer to the beginning for the next line from x++ fgets...
y++;//the idea with y=1000 is that I need another pointer to each struct field right?
}
for (x = 0; x < numStudents; x++)
printf("first name: %s, index: %d\n",students[x].name, students[x].index);
return students;
然后 printf 看看加载了什么。 (为了简化我有 6 个字段的真实结构)。我知道一个从用户输入加载 1 个学生的好方法...(How to scanf commas, but with commas not assigned to a structure? C)但是要加载多个,我有这个想法,但我不确定它是否太笨拙而无法工作或只是写得很糟糕。
稍后我会尝试按姓名对学生进行排序,甚至可能会尝试做一个 realloc 缓冲区,随着新学生被加载到缓冲区中,它的大小会增加......然后对什么进行排序已经加载...但我想首先我需要将它从文件加载到缓冲区,然后从缓冲区加载到填充结构,然后才能对其进行排序?...
非常感谢您的帮助!
【问题讨论】:
-
阅读C I/O functions的文档。
-
使用
students[x].name=(char*)malloc(sizeof(char*));分配一个大小的指针,这对于字符串来说是不够的。 -
在 sscanf 中,
&students[x].name是错误的,应该是students[x].name -
strtok只是将buffer切分成令牌,它不分配内存。 -
我怎样才能以其他方式命名我想做的事情,这样我才能用谷歌搜索它?在我提出问题之前,我至少会花 20 个小时来解决一个问题。我知道该怎么做是:从标准输入读取结构字段,从我知道字段长度的 bin 文件中读取,但这都是关于 1 个学生的。