您的位置:首页 > 编程语言 > C语言/C++

C语言读取文件数据到结构体数组

2018-01-06 18:58 225 查看
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct infostu
{
char no[20];				//学号
char name[20];
char sex[4];
int age;
char major[20];				//专业班级
};
int main()
{
int i=0,j;
struct infostu student[500];
FILE *fp;
if((fp=fopen("c:\\student.txt","r"))==NULL)			// 打开文件并且让fp指向 文件
{
printf("Can not open file\n");
exit(1);
}

while(!feof(fp))                     //读取一组数据后指针指向下一组数据,并且判断是否指向最后一行
{
fscanf(fp,"%[^,],%[^,],%[^,],%d,%s",&student[i].no,&student[i].name,&student[i].sex,&student[i].age,&student[i].major);
i++;
}             //%[^,]  字符串以,为结束标志
j=i;
for(i=0;i<j;i++)
printf("%s,%s,%s,%d,%s\n",student[i].no,student[i].name,student[i].sex,student[i].age,student[i].major);
fclose(fp);				//关闭文件;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐