cex_13_3.c

来自「C程序学习者学习文件操作的好讲义,包含例题,这个讲义是本人清手做的,花了很长时间」· C语言 代码 · 共 50 行

C
50
字号
#include "stdio.h"
#define SIZE 4
struct student_type
{
char name[10];
int num;
int age;
char addr[15];
}stud[SIZE];
void save(); /* 原型 */
void load(); /* 原型 */
void main()
{ int i;
  for(i=0; i<SIZE; i++) /* 从键盘读入数据 */
  scanf("%s%d%d%s",stud[i].name,&stud[i].num,&stud[i].age,stud[i].addr);save(); /* 存盘 */
  save();
  load();
  for(i=0; i<SIZE; i++) /* 屏幕上显示 */
   printf("%-10s%4d%4d%-15s\n", stud[i].name, stud[i].num, stud[i].age, stud[i].addr);
}
void save()   /* 写数据到磁盘文件*/
{ FILE *fp;
  int i;
  if ((fp=fopen("stu_list", "wb"))==NULL)
  {
    printf("can not open file\n");
    exit(0);
  }
  for(i=0; i<SIZE; i++)
  if (fwrite(&stud[i], sizeof(struct student_type), 1, fp) != 1)
  printf("file read error\n");
  fclose(fp);
}
void load()       /* 从盘读出 */
{ FILE *fp;
  int i;
  if ((fp=fopen("stu_list", "rb"))==NULL)
  {
  printf("can not open file\n");
  return;
  }
  for(i=0; i<SIZE; i++)
  if (fread(&stud[i], sizeof(struct student_type), 1, fp) != 1)
  {
  if (feof(fp)) return;
   printf("file read error\n");
  }
  fclose(fp);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?