C程序设计 (第四版) 谭浩强 例10.4
例10.4 从键盘输入10个学生的有关数据,然后把它们转存到磁盘文件上去。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法:使用指针,函数的模块化设计,动态分配内存
说明:这里准备先写入的文件名称为Test.txt,文件已经存在于该项目目录下。
#include <stdio.h>
#include <stdlib.h>#define N 10//定义学生结构体
typedef struct{int num;char name[20];int age;char addr[15];
}Student;//初始化变量
void initialVar(Student **stu, int n, char **name){*stu = (Student*)malloc(n * sizeof(Student));*name = (char*)malloc(20 * sizeof(char));
}//输入学生信息
void inputStu(Student *stu, int n){printf("Enter %d students info:\n\n", n);int i = 0;for(Student *p = stu; p < stu + n; p++, i++){printf("Enter No.%d student number(100 ~ 999): ", i + 1);scanf("%d", &p->num);while(p->num < 100 || p->num > 999){printf("Number Error! Retry!\nEnter No.%d student number(100 ~ 999): ", i + 1);scanf("%d", &p->num);}fflush(stdin);printf("Enter No.%d studnet name: ", i + 1);gets(p->name);printf("Enter No.%d student age(6 ~ 35): ", i + 1);scanf("%d", &p->age);while(p->age < 6 || p->age > 35){printf("Age Error! Retry!\nEnter No.%d student age(6 ~ 35): ", i + 1);scanf("%d", &p->age);}fflush(stdin);printf("Enter No.%d student address: ", i + 1);scanf("%s", p->addr);printf("\n");}printf("\n");
}//输出学生信息
void outputStu(Student *stu, int n){printf("Student Info:\n");for(Student *p = stu; p < stu + n; p++){printf("Number: %-3d Name: %-10s Age: %-2d Address: %-8s\n", p->num, p->name, p->age, p->addr);}printf("\n");
}//输入文件名并判断
void inputFileName(FILE **file, char *name){printf("Enter File Name: ");scanf("%s", name);*file = fopen(name, "rb");if(*file == NULL){perror("Cannot open this file");system("pause");exit(0);}*file = fopen(name, "wb");
}//将学生信息写入文件
void inputFile(FILE **file, Student *stu, int n){for(int i = 0; i < n; i++){if(fwrite(&stu[i], sizeof(Student), 1, *file) != 1){perror("File write error");system("pause");exit(0);}}fclose(*file);
}//读取文件中的学生信息
void outputFile(FILE **file, char *name, Student *stu, int n){*file = fopen(name, "rb");if(*file == NULL){perror("Cannot open this file");system("pause");exit(0);}printf("Read Student Info:\n");for(int i = 0; i < n; i++){fread(&stu[i], sizeof(Student), 1, *file);printf("Number: %-3d Name: %-10s Age: %-2d Address: %-8s\n", stu[i].num, stu[i].name, stu[i].age, stu[i].addr);}printf("\n");fclose(*file);
}//释放变量内存
void freeVar(Student **stu, char **name){free(*stu);free(*name);
}int main(){FILE *file = NULL;Student *stu = NULL;char *name = NULL;initialVar(&stu, N, &name);inputStu(stu, N);outputStu(stu, N);inputFileName(&file, name);inputFile(&file, stu, N);outputFile(&file, name, stu, N);freeVar(&stu, &name);system("pause");return 0;
}
运行结果如下: