#include "main.h" #include #include #include // Read a line from stdin, strip the eventual newline and return a pointer // to the string. Remember to free the pointer. char *read_input() { char *buf = NULL; size_t buf_size = 0; size_t read = getline(&buf, &buf_size, stdin); if (read == -1) { free(buf); buf = NULL; } else if (read >= 1 && buf[read - 1] == '\n') { buf[read - 1] = '\0'; } return buf; } int read_int() { char *buf = read_input(); int res = -1; if (!buf) { printf("Failed to read int from stdin\n"); } else { res = atoi(buf); } free(buf); return res; } // Fetch a student name from the terminal input and add it to the list. void insert(struct list *student_list) { struct student *student = malloc(sizeof(struct student)); char *name = read_input(); if (!name) { printf("Failed to read student name\n"); free(student); } else { student->name = name; printf("Inserted student with name '%s'\n", student->name); list_push_front(student_list, &student->elem); } } // Get a student name from the terminal input, remove it from the list and // deallocate the appropriate memory (if needed). void delete(struct list *student_list) { list(student_list); printf("Name of student to delete:\n"); char *name = read_input(); if (!name) { printf("Failed to read student name\n"); } else { struct list_elem *e; int removed_student = 0; for (e = list_begin(student_list); e != list_end(student_list); e = list_next(e)) { struct student *student = list_entry(e, struct student, elem); if (strcmp(student->name, name) == 0) { printf("Removing student '%s'\n", student->name); list_remove(&student->elem); free(student->name); free(student); removed_student = 1; break; } } if (!removed_student) { printf("No student named '%s' found\n", name); } } free(name); } // Print the entire list. void list(struct list *student_list) { struct list_elem *e; for (e = list_begin(student_list); e != list_end(student_list); e = list_next(e)) { struct student *student = list_entry(e, struct student, elem); printf("Student: %s\n", student->name); } } // Clear the list and deallocate the memory. void quit(struct list *student_list) { struct list_elem *e; struct student *student; while (!list_empty(student_list)) { e = list_pop_front(student_list); student = list_entry(e, struct student, elem); printf("Removing '%s'\n", student->name); free(student->name); free(student); } exit(0); } int main() { struct list student_list; list_init(&student_list); int opt; do { printf("Menu:\n"); printf("1 - Insert student\n"); printf("2 - Delete student\n"); printf("3 - List students\n"); printf("4 - Exit\n"); switch (read_int()) { case 1: { insert(&student_list); break; } case 2: { delete(&student_list); break; } case 3: { list(&student_list); break; } case 4: { quit(&student_list); break; } default: { printf("Quit? (1/0):\n"); if (read_int()) quit(&student_list); break; } } } while(1); return 0; }