#include #include #include #include "studlist04.h" int main(int argc, char *argv[]) { char filename[40], mode; FILE *fp; Record r; /* open input file */ if (argc >= 2) strcpy(filename, argv[1]); else strcpy(filename, "Student.txt"); if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Cannot open %s!\n", filename); exit(2); } /* initialize */ head = make_1node(r, NULL); /* sort mode : Descending/Ascending */ printf("Enter sort mode (d:descending / a:ascending) -> "); scanf( " %c", &mode ); if (!(mode == 'd' || mode == 'a')) { printf("Enter d or a\n"); exit(1); } /* read data from file */ while (fscanf(fp, "%d %s %s %d", &r.id, r.surname, r.givenname, &r.age) != EOF) { if(insert_sort(r, mode) == 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("Insert new student data: (ID Surname Givenname Age) -> "); if (scanf("%d %s %s %d", &r.id, r.surname, r.givenname, &r.age) != 4) { printf("\n"); break; } if (insert_sort(r,mode) == NULL) { printf("ID %d is already on the list!\n", r.id); } listprint(); } return 0; } /* insert one node in descending or ascending order */ /* return pos(inserted), NULL(already exist) */ /* mode-> d:descending / a:ascending */ NodePointer insert_sort(Record r, char mode) { NodePointer n, newnode; if (finditem(r.id) != NULL) return NULL; for(n = head; n->next != NULL; n = n->next) { if (mode == 'd') { if ( n->next->data.id <= r.id ) break; } else { /* mode == 'a' */ if ( n->next->data.id >= r.id ) break; } } newnode = make_1node(r,n->next); n->next = newnode; return newnode; } /* 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; }