C/C++ 读取文件内容到结构体数组中。。

22.txt

2016 AAAA 20160001 11111111111 25 88.0 99.5 99.0 77.0 63.5
2016 BBB 20160002 11111111111 25 88.0 99.5 99.0 77.0 63.5
2016 CCC 20160003 11111111111 25 88.0 99.5 99.0 77.0 63.5
2016 DDDD 20160004 11111111111 25 88.0 99.5 99.0 77.0 63.5
2016 EEEEE 20160005 11111111111 25 88.0 99.5 99.0 77.0 63.5


建立的一个简单的结构体,以方便演示操作。。

struct Student
{
	int nYear;
	char czName[20];
	char czNumber[10];
	char czTel[12];
	int nAge;
	float fScore[5];
}Student[10];

int main()
{ 
	int nCount = 0;
	FILE *fp = fopen("22.txt","rb");
	if(fp == NULL)
	{ 
		printf("can not open file!\n");
		exit(0);
	}
	for(int i = 0;i < 100;i ++)
	{
		int nRes = fscanf(fp,"%d %s %s %s %d %f %f %f %f %f",&Student[i].nYear,Student[i].czName,Student[i].czNumber,Student[i].czTel,
			&Student[i].nAge,&Student[i].fScore[0],&Student[i].fScore[1],&Student[i].fScore[2],&Student[i].fScore[3],&Student[i].fScore[4]);
		if (nRes == -1)
		{
			nCount = i;
			fclose(fp);
			break;
		}		
	}

	for (int i = 0;i < nCount;i ++)
	{
		printf("%d %s %s %s %d %.2f %.2f %.2f %.2f %.2f\n",Student[i].nYear,Student[i].czName,Student[i].czNumber,Student[i].czTel,
			Student[i].nAge,Student[i].fScore[0],Student[i].fScore[1],Student[i].fScore[2],Student[i].fScore[3],Student[i].fScore[4]);
	}
	fclose(fp);
	return 0;
}


主要的使用函数:

int fscanf(    FILE* stream,    const char* format [, argument ]... );
int fwscanf(    FILE* stream,    const wchar_t* format [, argument ]... );



  • 10
    点赞
  • 95
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值