#include #include #include #include "student.h" // Creates a student based on user input and returns a pointer to that student student_t * create_student() { student_t *student = (student_t*)malloc(sizeof(student)); printf("Enter student id:\n\n"); scanf("%i", &student->id); getchar(); // Remove the newline from the buffer printf("Enter student name:\n\n"); fgets(student->name, sizeof(student->name), stdin); student->name[(size_t)strlen(student->name) - 1] = '\0'; // Remove the newline from end of the array printf("Enter student age:\n\n"); scanf("%i", &student->age); getchar(); // Remove the newline from the buffer return student; } // Reads information from a text file and returns a pointer to a student with that information student_t * read_student_file() { student_t *student = (student_t*)malloc(sizeof(student)); FILE *f = fopen("student_read.txt", "r"); fscanf(f, "%i\n", &student->id); fgets(student->name, sizeof(student->name), f); student->name[strlen(student->name) - 1] = '\0'; fscanf(f, "%i\n", &student->age); fclose(f); return student; } // Reads information from a previously created student and writes that information to a text file void write_student_file( student_t * student ) { FILE *f = fopen("student_write.txt", "w"); fprintf(f, "%i\n", student->id); fprintf(f, "%s\n", student->name); fprintf(f, "%i\n", student->age); printf("Information has been written to 'student_write.txt'\n\n"); fclose(f); free(student); // Free the memory we previously allocated for a student } // Print information about a given student void print_student( student_t * student ) { printf("Student id: %i\n", student->id); printf("Name: %s\n", student->name); printf("Age: %i\n\n", student->age); // Extra newline for better formatting free(student); // Free the memory we previously allocated for a student } // Prints a menu of options that loops continually until the user chooses to exit the program. void show_menu() { int user_choice; do { printf("1. Read student information from file\n"); printf("2. Write student information to file\n"); printf("3. Exit\n\n"); // Extra newline for better formatting scanf("%i", &user_choice); switch(user_choice) { case 1: print_student( read_student_file() ); // Read student information from a file and print it back out break; case 2: write_student_file( create_student() ); // Get student information from user and write it to a file break; case 3: printf("You have chosen to exit the program\n"); break; default: // Handle wrong input from the user printf("Error, please review that you entered a number between 1 and 3\n"); } } while(user_choice != 3); }