This commit is contained in:
Tančáková 2024-03-22 08:19:34 +01:00
parent c262b5c146
commit 327e8f8d5d

View File

@ -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);