funguje
This commit is contained in:
parent
c262b5c146
commit
327e8f8d5d
@ -23,17 +23,11 @@ int compare(const void *p1, const void *p2) {
|
|||||||
return strcmp(s1->name, s2->name);
|
return strcmp(s1->name, s2->name);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Načíta študentov zo súboru do pola
|
// Načíta študentov zo súboru alebo zo štandardného vstupu do pola
|
||||||
int read_students_from_file(struct Student students[], int max_students) {
|
int read_students(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;
|
|
||||||
}
|
|
||||||
|
|
||||||
int num_students = 0;
|
int num_students = 0;
|
||||||
char line[MAX_SIZE];
|
char line[MAX_SIZE];
|
||||||
while (fgets(line, sizeof(line), file) != NULL) {
|
while (fgets(line, sizeof(line), stdin) != NULL) {
|
||||||
int votes;
|
int votes;
|
||||||
char name[MAX_SIZE];
|
char name[MAX_SIZE];
|
||||||
if (sscanf(line, "%d %99[^\n]", &votes, name) == 2) {
|
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;
|
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() {
|
int main() {
|
||||||
struct Student students[MAX_STUDENTS];
|
struct Student students[MAX_STUDENTS];
|
||||||
int num_students = read_students_from_file(students, MAX_STUDENTS);
|
int num_students = read_students(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);
|
|
||||||
|
|
||||||
// Zoradíme študentov podľa počtu hlasov
|
// Zoradíme študentov podľa počtu hlasov
|
||||||
qsort(students, num_students, sizeof(struct Student), compare);
|
qsort(students, num_students, sizeof(struct Student), compare);
|
||||||
|
Loading…
Reference in New Issue
Block a user