51 lines
1.1 KiB
C
51 lines
1.1 KiB
C
#include <stdio.h>
|
|
|
|
|
|
struct Person {
|
|
int age;
|
|
int year_of_birth;
|
|
char forename[30];
|
|
char surname[50];
|
|
};
|
|
|
|
|
|
void print_person(struct Person p) {
|
|
printf("p.age=%d p.year_of_birth=%d p.forename=%s p.surname=%s\n", p.age, p.year_of_birth, p.forename, p.surname);
|
|
}
|
|
|
|
|
|
int main() {
|
|
struct Person p;
|
|
FILE *fp;
|
|
char choice;
|
|
char filename[4097];
|
|
|
|
printf("Read or write a file? (r/w) "); scanf("%c", &choice);
|
|
|
|
if (choice == 'w') {
|
|
printf("Enter age: "); scanf("%d", &p.age);
|
|
printf("Enter birth year: "); scanf("%d", &p.year_of_birth);
|
|
printf("Enter forename: "); scanf("%29s", p.forename);
|
|
printf("Enter surname: "); scanf("%49s", p.surname);
|
|
|
|
printf("Enter filename to save to: "); scanf("%4096s", filename);
|
|
fp = fopen(filename, "wb");
|
|
if (fp == NULL) {
|
|
printf("Failed to open file for writing\n");
|
|
return 1;
|
|
}
|
|
fwrite(&p, 1, sizeof(p), fp);
|
|
} else {
|
|
printf("Enter file to read from: "); scanf("%4096s", filename);
|
|
fp = fopen(filename, "rb");
|
|
if (fp == NULL) {
|
|
printf("Failed to open file for reading\n");
|
|
return 1;
|
|
}
|
|
fread(&p, 1, sizeof(p), fp);
|
|
}
|
|
|
|
print_person(p);
|
|
return 0;
|
|
}
|