C语言中怎么把磁盘中的TXT文件读入到结构体中

如题所述

参考下面:
#include <stdio.h>

void main()
{
FILE* fp;
struct student {
int num;
char name[20];
};
struct student std = {1, "xiao sa ge"}, std1;

if((fp=fopen("test.txt","w"))==NULL)
{
printf("you can not open the file ~!!");
exit(0);
}

if((fwrite(&std,sizeof(struct student),1,fp))!=1)
{
printf("error");
exit(0);
}
fclose(fp);

if((fp=fopen("test.txt","r"))==NULL)
{
printf("you can not open the file ~!!");
exit(0);
}

if (fread(&std1,sizeof(struct student),1,fp)!=1)
{
printf("error!");
exit(0);
}

printf("%d, %s\n", std1.num, std1.name);

fclose(fp);
}
温馨提示:答案为网友推荐,仅供参考
相似回答