修改文件结构。
This commit is contained in:
88
POP/14/Exercise01.c
Normal file
88
POP/14/Exercise01.c
Normal file
@@ -0,0 +1,88 @@
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#define MALE false
|
||||
#define FEMALE true
|
||||
|
||||
typedef struct {
|
||||
int year;
|
||||
int month;
|
||||
int date;
|
||||
} DATE;
|
||||
|
||||
typedef struct {
|
||||
int ID;
|
||||
char name[21];
|
||||
bool sex;
|
||||
DATE birthday;
|
||||
double score;
|
||||
} STUDENT;
|
||||
|
||||
void saveStu(STUDENT students[], int count) {
|
||||
int i;
|
||||
FILE* fileObj;
|
||||
for (i = 0; i < count; i++) {
|
||||
printf("ID: ");
|
||||
scanf("%d", &students[i].ID);
|
||||
printf("Name(max 20 char): ");
|
||||
scanf("%20s", students[i].name);
|
||||
printf("Sex: (MALE-0/FEMLE-1)");
|
||||
scanf("%d", &students[i].sex);
|
||||
printf("Birthday (Year/Month/Date):");
|
||||
scanf("%d/%d/%d", &students[i].birthday.year, &students[i].birthday.month, &students[i].birthday.date);
|
||||
printf("Scores:\n");
|
||||
scanf("%lf", &students[i].score);
|
||||
}
|
||||
fileObj = fopen("studentInfos", "wb");
|
||||
if (fileObj == NULL) {
|
||||
printf("Cannot open file.\n");
|
||||
return;
|
||||
}
|
||||
if (fwrite(students, sizeof(STUDENT), count, fileObj) == 0) {
|
||||
printf("Print file error.\n");
|
||||
}
|
||||
fclose(fileObj);
|
||||
}
|
||||
|
||||
void loadStu(STUDENT students[], int count) {
|
||||
int i;
|
||||
FILE* fileObj;
|
||||
int targetID;
|
||||
fileObj = fopen("studentInfos", "rb");
|
||||
if (fileObj == NULL) {
|
||||
printf("Cannot open file.\n");
|
||||
return;
|
||||
}
|
||||
if (fread(students, sizeof(STUDENT), count, fileObj) == 0) {
|
||||
printf("Read error.\n");
|
||||
return;
|
||||
}
|
||||
fclose(fileObj);
|
||||
printf("Loaded.\n");
|
||||
printf("ID to be checked: ");
|
||||
scanf("%d", &targetID);
|
||||
for (i = 0; i < count; i++) {
|
||||
if (targetID == students[i].ID) {
|
||||
printf("ID:%d; Name: %s; Sex:%s; Birthday:%d/%d/%d; Score:%lf\n", students[i].ID, students[i].name, students[i].sex?"FEMALE":"MALE", students[i].birthday.year, students[i].birthday.month, students[i].birthday.date, students[i].score);
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
STUDENT students[10];
|
||||
int i = 0;
|
||||
int count = 3;
|
||||
char mode;
|
||||
// freopen("fakedata","r",stdin);
|
||||
printf("Select: (S)ave/(L)oad ");
|
||||
scanf("%c", &mode);
|
||||
if (mode == 's' || mode == 'S') {
|
||||
saveStu(students, count);
|
||||
}
|
||||
else if (mode == 'l' || mode == 'L') {
|
||||
loadStu(students, count);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user