将文件数据读入结构体

将文件数据读入结构体

#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;
}

  • 3
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解答这个问题。首先,你需要定义一个结构体,该结构体应该包含你想要在文件存储的数据类型。例如,如果你想要从文件读取学生的姓名、年龄和分数,那么你可以定义如下的结构体: ```c typedef struct { char name[20]; int age; float score; } Student; ``` 接下来,你需要打开文件并读取数据。你可以使用`fscanf`函数从文件读取数据,并将其存储在结构体数组。假设你的文件名为`data.txt`,你可以使用如下的代码将文件数据读入结构体数组: ```c #include <stdio.h> int main() { FILE *fp; Student students[100]; int count = 0; fp = fopen("data.txt", "r"); if (fp == NULL) { printf("Failed to open file!\n"); return 1; } while (fscanf(fp, "%s %d %f", students[count].name, &students[count].age, &students[count].score) == 3) { count++; } fclose(fp); // 现在你可以使用数据了 for (int i = 0; i < count; i++) { printf("Name: %s, Age: %d, Score: %.2f\n", students[i].name, students[i].age, students[i].score); } return 0; } ``` 在上面的代码,我们首先打开了`data.txt`文件并检查是否成功。然后,我们使用`fscanf`函数从文件读取数据,并将其存储在结构体数组`students`。每次成功读取一行数据时,我们将计数器`count`增加1。最后,我们使用一个循环遍历结构体数组数据,并将其打印出来。 希望这可以回答你的问题。如果你还有其他问题,请随时问我。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值