#include #include #include #include "studlist10.h" int main() { char *filename="Student.txt"; FILE *fp; Record r; char selstr[20]; /* initialize */ head = make_1node( r, NULL ); /* input data from file */ if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Cannot open %s!\n", filename); exit(1); } while (fscanf(fp, "%d %s %s %d", &r.id, r.surname, r.givenname, &r.age) != EOF) { if(insert(r) == NULL) printf("Error: %d appears twice in the file.\n", r.id); /* ここのメッセージは適当。なくてもよい */ } fclose(fp); listprint(); /* insert list member */ /* CTL+D to escape this loop */ while (1) { printf("Input match data (ID) -> "); if (scanf("%s", selstr) != 1) { printf("\n"); break; } listprint_sel(selstr); } return 0; } /* First, find item r, based on data ID */ /* If the ID is not found, insert r after the last node */ /* Return value: node(inserted), NULL(already exist) */ NodePointer insert(Record r) { NodePointer newnode, n; if (finditem(r.id) == NULL) { /* new node creation (if the item is not found) */ newnode = make_1node(r, NULL); /* trace nodes from head to tail */ for ( n=head; n->next!=NULL; n=n->next ); n->next = newnode; /* link new node to the last node */ return newnode; } else return NULL; } /* print all items in the list from head to tail */ void listprint(void) { NodePointer n; int count = 0; printf("Head - \n"); for(n = head->next; n != NULL; n = n->next){ printf(" %7d %-12s %-12s %d\n", n->data.id, n->data.surname, n->data.givenname, n->data.age); count++; } printf("%d nodes exist in the list.\n", count); printf("\n"); } /* find item id_data with given ID */ /* if found, return the address of the previous node. */ /* otherwise, return NULL */ NodePointer finditem(int sid) { NodePointer n; for(n = head; n->next != NULL; n = n->next) { if(n->next->data.id == sid) return n; } return NULL; } NodePointer make_1node(Record r, NodePointer p) { NodePointer n; if ((n = (NodePointer) malloc(sizeof(struct node)) ) == NULL) { printf("Error in memory allocation\n"); exit(8); } n->data = r; n->next = p; return n; } /* print all items in the list from head to tail */ void listprint_sel(char *str) { NodePointer n; char numstr[20]; for(n = head->next; n != NULL; n = n->next){ sprintf(numstr, "%d", n->data.id); if (strncmp(numstr, str, strlen(str))==0) { printf(" %7d %-12s %-12s %d\n", n->data.id, n->data.surname, n->data.givenname, n->data.age); } } printf("\n"); }