从键盘输入4个学生的有关数据,然后把他们存放到一个名为stu_list.txt的磁盘文件中去,并在屏幕上显示。


代码如下:

				
#include<stdio.h>
#include<stdlib.h>
#define SIZE 4

struct student
{
     char name[15];
     char number[15];
     int score;
     char address[15];
}stu[SIZE];

void save()//定义save函数,向文件中写入数据
{
     FILE *fp;
     int i;
     if((fp=fopen("stu_list.txt","wb"))==NULL)
     {
         printf("cannot open file\n");
         exit(0);
     }
     for(i=1;i<=SIZE;i++)
     {
         if(fwrite(&stu[i],sizeof(structstudent),1,fp)!=1)
             printf("file write error\n");
     }
     fclose(fp);
}

void view()//定义view函数,读取文件数据并在屏幕上显示
{
     FILE *fp;
     int i;
     if((fp=fopen("stu_list.txt","rb"))==NULL)
     {
         printf("cannot open file\n");
         exit(0);
     }
     for(i=1;i<=SIZE;i++)
     {
         if(fread(&stu[i],sizeof(structstudent),1,fp)==1)
             printf("%-15s%-15s%-6d%-15s\n",stu[i].name,stu[i].number,stu[i].score,stu[i].address);
         else
             printf("file read error\n");
     }
     fclose(fp);
}

int main()
{
     for(int i=1;i<=SIZE;i++)
     {
         printf("Please input %dth student's information:\n",i);
         printf("Name:");
         gets(stu[i].name);
         printf("Number:");
         gets(stu[i].number);
         printf("Score:");
         scanf("%d",&stu[i].score);
         getchar();
         printf("Address:");
         gets(stu[i].address);
     }
     save();
     view();
     return 0;
}




联系我们 | 友情链接