//
// Created by 冲哥 on 2021/2/24.
// 关注公众号【C语言中文社区】,和更多C语言爱好者一块学习。
//
#include<stdio.h>
#include<process.h>
struct StuInfo {
char name[20];
char gender[2];
int age;
} info[100];
void save_info(char *filename, int n) {
FILE *fp;
int i;
if ((fp = fopen(filename, "wb")) == NULL) {
printf("open file error!\n");
exit(0);
}
for (int i = 0; i < n; i++) {
if (fwrite(&info[i], sizeof(struct StuInfo), 1, fp) != 1) {
printf("write error!\n");
}
}
fclose(fp);
}
void show_info(char *filename, int n) {
FILE *fp;
if ((fp = fopen(filename, "rb")) == NULL) {
printf("open file error!\n");
exit(0);
}
for (int i = 0; i < n; i++) {
fread(&info[i], sizeof(struct StuInfo), 1, fp);
printf("%20s%10s%10d", info[i].name, info[i].gender, info[i].age);
}
fclose(fp);
}
int main(){
int i, n;
char filename[50];
printf("how many info will be write?\n");
scanf("%d", &n);
printf("please input the filename:\n");
scanf("%s", filename);
printf("please input the name,gender,age:\n");
for (int j = 0; j < n; j++) {
printf("NO%d\n", j+1);
scanf("%s,%s,%d", info[j].name, info[j].gender, info[j].age);
save_info(filename, n);
}
show_info(filename, n);
return 0;
}