From 327e8f8d5d9fd62295a86a973f19dcb848400174 Mon Sep 17 00:00:00 2001 From: st529yr Date: Fri, 22 Mar 2024 08:19:34 +0100 Subject: [PATCH] funguje --- cv5/program.c | 36 ++++-------------------------------- 1 file changed, 4 insertions(+), 32 deletions(-) diff --git a/cv5/program.c b/cv5/program.c index 60f72b1..5baad49 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -23,17 +23,11 @@ int compare(const void *p1, const void *p2) { return strcmp(s1->name, s2->name); } -// Načíta študentov zo súboru do pola -int read_students_from_file(struct Student students[], int max_students) { - FILE *file = fopen("nazov_suboru.txt", "r"); - if (file == NULL) { - perror("Chyba pri otváraní súboru"); - return -1; - } - +// Načíta študentov zo súboru alebo zo štandardného vstupu do pola +int read_students(struct Student students[], int max_students) { int num_students = 0; char line[MAX_SIZE]; - while (fgets(line, sizeof(line), file) != NULL) { + while (fgets(line, sizeof(line), stdin) != NULL) { int votes; char name[MAX_SIZE]; if (sscanf(line, "%d %99[^\n]", &votes, name) == 2) { @@ -45,34 +39,12 @@ int read_students_from_file(struct Student students[], int max_students) { } } } - - fclose(file); return num_students; } -// Pridá nového študenta do súboru -void add_student_to_file(const struct Student *student) { - FILE *file = fopen("nazov_suboru.txt", "a"); - if (file == NULL) { - perror("Chyba pri otváraní súboru"); - return; - } - fprintf(file, "%d %s\n", student->votes, student->name); - fclose(file); -} - int main() { struct Student students[MAX_STUDENTS]; - int num_students = read_students_from_file(students, MAX_STUDENTS); - if (num_students == -1) { - return 1; // Chyba pri čítaní zo súboru - } - - // Pridáme nového študenta - struct Student new_student; - strcpy(new_student.name, "Novy Student"); - new_student.votes = 5; - add_student_to_file(&new_student); + int num_students = read_students(students, MAX_STUDENTS); // Zoradíme študentov podľa počtu hlasov qsort(students, num_students, sizeof(struct Student), compare);