|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
练习用c写个键盘交互输入结构体并存到文件的小程序,编译通过。但是运行后发现保存的内容在读出来的时候有格式问题(有可能是其他问题)。求大神帮忙看看问题出在哪里。
#include<stdio.h>
typedef struct {
int age;
char gend[10];
char name[10];
}student;
int SIZE=sizeof(student);
void add(FILE *records );
void read(FILE *records );
void main()
{
FILE *records;
if(NULL==(records=fopen("D:\\Personal\\Computer\\students","wb")))
{
printf("Can not open the file");
return;
}
while(1)
{
printf("1:add a new student record\n");
printf("2:find a new student record\n");
printf("3:deleted a student record\n");
printf("0:exit\n");
printf("Please enter your choices:");
int choice;
scanf("%d",&choice);
switch(choice)
{
case 1:
add(records );
break;
case 2:
read(records );
break;
case 0:
return;
}
}
}
void add(FILE *records )
{
student std;
printf("Please enter student age:");
scanf("%d", &std.age);
printf("Please enter student gend:");
scanf("%s", std.gend);
printf("Please enter student name:");
scanf("%s", std.name);
if(fwrite(&std,SIZE,1,records)!=1)
{
printf("file write error\n");
fclose(records);
}
else{
printf("file write successfully\n");
}
return;
}
void read( FILE *records)
{
student std;
int nub;
printf("how many records to show:");
scanf("%d",&nub);
fseek(records,0,SEEK_SET);
fread(&std,SIZE,nub,records);
for(int i=0;i<nub;i++)
{
printf("%d\t%s\t%s\t\n",std.age,std.gend,std.name);
}
return;
} |
|