#include #include #include #ifdef EBUG #define DEBUG(m) \ printf("debug: %s at line %d in file %s\n", \ (m), __LINE__, __FILE__) #else #define DEBUG(m) #endif struct Staff { char name[50]; int age; struct Staff * next; }; const char * FILENAME = "staffList.txt"; struct Staff * head = NULL; /* Recursively print the content of , in post-order. */ void printList(struct Staff* h) { if (!h) return; printList(h->next); printf(">> %s, %d\n", h->name, h->age); } /* Add to the first node of return the processed list */ struct Staff * addNode(struct Staff * h, struct Staff * n) { if (!n) return h; /* do nothing if n is NULL */ n->next = h; return n; } void calcAvgAge(struct Staff * h) { int total = 0, staffNum = 0; for (; h; ++staffNum, h=h->next) total += h->age; printf("Average age: %.2f\n", (float)total/staffNum); } /* Recursively search for in list Return the found node, or NULL if not found */ struct Staff * inList(struct Staff * h, char* name) { if (!h) return NULL; char fname[200], lname[200]; sscanf(h->name, "%s %s", fname, lname); if (strcmp(lname, name)) /* not found; keep trying */ return inList(h->next, name); return h; /* found */ } /* Write the content of list into */ void writeToFile(struct Staff * h) { FILE * outfile = fopen(FILENAME, "w"); while (h) { fprintf(outfile, "%s:%d\n", h->name, h->age); h = h->next; } fclose(outfile); } /* Remove the node from list , if exists. Return the processed list */ struct Staff * removeNode(struct Staff * h, struct Staff * r) { struct Staff * prev = NULL, *head = h; while(h) { if (h == r) { /* special case: if the match found at the first node */ if (prev == NULL) { h = h->next; free(r); return h; } prev->next = h->next; free(r); return head; } prev = h; h = h->next; } } int main() { FILE * infile; char line[257], name[256], toDel[10]; int age; struct Staff * temp = NULL; /* if file open failed, exit with signal status 1 */ if (!(infile = fopen(FILENAME, "r"))) exit(1); DEBUG("Start processing the file"); while (fgets(line, 256, infile)) { sscanf(line, "%[^:]:%d", name, &age); DEBUG("Populating the node"); temp = malloc(sizeof(struct Staff)); temp->next = NULL; strcpy(temp->name, name); temp->age = age; head = addNode(head, temp); } DEBUG("Start prompting..."); /* prompt for a last name to search for */ while (1) { printf("Enter a last name: "); scanf("%s", name); if (strcmp(name, "q") == 0) return 0; if (strcmp(name, "w") == 0) { writeToFile(head); continue; } if (temp = inList(head, name)) { printf(">> %s, %d\n", temp->name, temp->age); /* prompt user to remove the found record */ printf("Delete this person? [yes/NO] "); scanf("%s", toDel); DEBUG("Scanned user's input"); if (strcmp(toDel, "yes") == 0) { DEBUG("Removing the person..."); head = removeNode(head, temp); } #ifdef EBUG printList(head); #endif } else { printf("not found!\n"); } } //printList(head); //calcAvgAge(head); return 0; }