怎样把TXT格式文件中以记录存在的数据读到C语言结构体数组中

我想把文本文件中的记录读到结构体的数组中,记录部分如下:
分类号 书名 作者 出版社
F224.32/7492 博弈学习理论 陈学彬 上海财经大学出版社 1
F224.32/0027 博弈论基础 高峰 中国社会科学出版社 1
F224.3/8023 经济博弈分析 全贤唐 机械工业出版社
请高手指点,谢谢!!!

第1个回答  推荐于2016-04-22
#include <stdio.h>
#include <stdlib.h>
struct content
{
char id[100];
char bookname[100];
char editorname[100];
char publishname[100];
struct content *next;
};
int main()
{
FILE *fp;///读文件用的文件指针
char root[1000];///记录文件所在的目录
scanf("%s",root);///输入文件所在的目录
fp=fopen(root,"r");///打开文件
if (fp==NULL)///如果文件指针为空,报错
{
printf("无法打开文件!\n");
return 0;
}
struct content *p1,*p2=NULL;
p1=(struct content*)calloc(1,sizeof(struct content));
p2=p1;
while (fscanf(fp,"%s",p1->id)==-1)
{
fscanf(fp,"%s",p1->bookname);
fscanf(fp,"%s",p1->editorname);
fscanf(fp,"%s",p1->publishname);
p2->next=p1;
p2=p1;
p2->next=NULL;
p1=(struct content*)calloc(1,sizeof(struct content));
}
return 0;
}

这是代码,没测试过,不知道对吧,高手不敢当,希望对你有用本回答被提问者和网友采纳
第2个回答  推荐于2016-09-20
首先你得知道文件记录的格式是什么样的。
比如说,文件中存的是学生的成绩。
学号 语文 数学
1001 80 90
1002 85 59
……
1、定义结构体信息
struct student
{
char no[10];
float chinese;
float math;
};
2、定义一个结构体数组,用来存所有学生的信息
struct student s[100];
3、读取每一行信息
fscanf("%s %f %f",s[i].no,&s[i].chinese,&s[i].math);
相似回答