person.c (1930B)
1 /* Exercise 11.11 */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 #define REC 100 8 9 struct person { 10 char lastName[15]; 11 char firstName[15]; 12 char age[4]; 13 }; 14 15 int main(void) 16 { 17 struct person empty = { "unassigned", "", "0" }; 18 struct person guy = { "unassigned", "", "0" }; 19 FILE *fd; 20 int i; 21 22 if( (fd = fopen("nameage.dat", "w")) == NULL) { 23 printf("cannot open the file \"%s\"\n", "nameage.dat"); 24 exit(-1); 25 } 26 27 /* --- A --- */ 28 29 /* write the recors */ 30 for(i = 0; i < REC; i++) { 31 fwrite(&empty, sizeof(struct person), 1, fd); 32 } 33 34 /* --- B --- */ 35 36 /* insert ten entries of Surname, name and age to the file */ 37 for(i = 0; i < 10; i++) { 38 printf("Surname, name and age: "); 39 scanf("%s%s%s", guy.lastName, guy.firstName, guy.age); 40 fwrite(&guy, sizeof(struct person), 1, fd); 41 } 42 43 /* --- C --- */ 44 45 /* seek to one of the ten latest entries */ 46 fseek(fd, 100 + rand() % 10 * sizeof(struct person), SEEK_SET); 47 48 fread(&guy, sizeof(struct person), 1, fd); 49 if( ! strncmp(guy.lastName, "unassigned", sizeof(guy.lastName)) && 50 ! strncmp(guy.firstName, "", 1) && ! strncmp(guy.age, "", 1) ) { 51 52 printf("No info\n"); 53 54 } 55 printf("\n[update]: Surname, name and age: "); 56 scanf("%s%s%s", guy.lastName, guy.firstName, guy.age); 57 fwrite(&guy, sizeof(struct person), 1, fd); 58 59 /* --- D --- */ 60 61 fseek(fd, 100 * sizeof(struct person), SEEK_SET); 62 63 for(i = 100; i < 110 && !feof(fd); i++) { /* feof() not required */ 64 if( strncmp(guy.lastName, "unassigned", sizeof(guy.lastName)) || 65 strncmp(guy.firstName, "", 1) || strncmp(guy.age, "", 1) ) { 66 i = 1; 67 break; 68 } 69 fread(&guy, sizeof(struct person), 1, fd); 70 } 71 72 if(i == 1) { 73 fwrite(&empty, sizeof(struct person), 1, fd); 74 } 75 else { 76 printf("No empty records!\n"); 77 } 78 79 80 fclose(fd); 81 82 return 0; 83 } /* E0F main */ 84