# 16.	 Текстовые файлы. Функции для работы с текстовыми файлами. Алгоритмы работы с текстовыми файл

## Текстовые файлы

**Текстовые файлы** - файлы, содержащие текстовые данные, организованные в виде строк. При работе с текстовым файлом нужно помнить, что это файлы последовательного доступа, для каждого действия нужно открывать файл заново на нужный режим.

<figure><img src="https://3074527236-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FOlTieA4l7aQXw27w94AS%2Fuploads%2FDJg3Dq0HUygmBEOJq5Ni%2Fimage.png?alt=media&#x26;token=858bd503-13e6-449b-a209-8c481dc69cfd" alt=""><figcaption></figcaption></figure>

### Алгоритм работы: <a href="#algoritm-raboty" id="algoritm-raboty"></a>

1. Открыть файл
2. Сделать проверку, открылся ли файл
3. Записать/считать данные из файла
4. Закрыть файл

Сортировка/удаление

1. Открыть файл на чтение
2. Проверить на открытие
3. Считать значения из файла в массив
4. Отсортировать массив/удалить элемент из массива
5. Открыть файл на запись (он очистится)
6. Записать измененный массив в файл

### Функции для работы с текстовыми файлами. <a href="#funkcii-dlya-raboty-s-tekstovymi-fai-lami." id="funkcii-dlya-raboty-s-tekstovymi-fai-lami."></a>

* Открытие файлового потока. Возвращает указатель на поток

`FILE* fopen (const char* имя, const char* режим открытия);`

* Закрытие файлового потока

`void fclose (FILE* ptrFile);`

* Запись в файл. Возвращает общее количество записанных символов

`int fprintf (FILE* ptrFile, const char* format, ...);`

* Чтение из файла. Возвращает количество аргументов, которым действительно были присвоены значения. Если при чтении была сделана попытка выйти за конец файла, то возвращается EOF.

`int fscanf(FILE* ptrFile, const char* format, …);`

* Записывает строку в файл (не добавляет \n). В случае успеха возвращается неотрицательное значение, иначе - EOF.

`int fputs(const char * string, FILE * ptrFile);`

* Считывает указанное количество символов в строку. В конце добавляет \n\0. В случае успеха возвращает указатель на строку. При ошибке возвращает NULL

`char * fgets(char * string, int num, FILE * ptrFile);`

* Возвращает символ из файла. При ошибке возвращает EOF

`int fgetc(FILE * ptrFile);`​

```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define FILE_EXIST 1
#define FILE_NOT_EXIST 0
 
typedef struct Student_t {
    char surname[20];
    int group;
    int grades[3];
} student;
 
student *readStudent(int *c);
void input();
void workStudents(student *arrayOfStudent, int c);
void workSort(student *arrayOfStudent, int c);
void outputStudents();
void swap(student *a, student *b);
int checkFile(const char *filename);
int *reallocGroup(int *group, int *size);
 
int main(){
    char *file = ("aaa.txt");
    if (checkFile(file) == FILE_NOT_EXIST) {
        input();
    }
    else{
        printf("File exist\n");
    }
    int c = 0;
    student *arrayOfStudent = readStudent(&c);
    if (arrayOfStudent != NULL){
        workStudents(arrayOfStudent, c);
        outputStudents();
    }
    return 0;
}
 
int checkFile(const char *filename){
    int result = FILE_EXIST;
    FILE *file = fopen(filename,"r");
    if (file == NULL){
        result = FILE_NOT_EXIST;
    }
    else{
        fclose(file);
    }
    return result;
}
 
void outputStudents(){
    FILE *file = fopen("aaa.txt", "r");
    if(file != NULL){
        student temp;
        while(fscanf(file, "%20s %d %d %d %d", temp.surname, &temp.group, &temp.grades[0], &temp.grades[1], &temp.grades[2]) != EOF){
            printf("%s %d %d %d %d\n", temp.surname, temp.group, temp.grades[0], temp.grades[1], temp.grades[2]);
        }
        fclose(file);
    }
}
 
int *reallocGroup(int *group, int *size){
    *size = *size + 1;
    group = (int*)realloc(group,sizeof(int) * (*size));
    return group;
}
 
void workStudents(student *arrayOfStudent, int c){
    int size = 1;
    int *group = malloc(sizeof(int) * size);
    *group = (arrayOfStudent)->group;
    for(int i = 0; i < c; i++){
        int tempGroup = (arrayOfStudent+i)->group;
        int res = -1;
        for(int k = 0; k < size; k++){
            if(tempGroup != *(group+k)) {
                res = 1;
            }
        }
        if(res == 1){
            group = reallocGroup(group, &size);
            if(group == NULL) {
                break;
            }
            *(group + i) = (arrayOfStudent+i)->group;
        }
    }
    double avgGrades[size];
    for(int i = 0; i < size; i++){
        int l = 0;
        for(int k = 0; k < c; k++){
            double avg = 0;
            if((arrayOfStudent+k)->group == *(group+i)){
                l++;
                avg = ((arrayOfStudent+k)->grades[0] + (arrayOfStudent+k)->grades[1] + (arrayOfStudent+k)->grades[2]) / 3;
            }
            avgGrades[i] += avg;
        }
        avgGrades[i] = avgGrades[i]/l;
    }
    double min = avgGrades[0];
    int g = *group;
    for(int i = 0; i < size; i++){
        if(min > avgGrades[i]){
            min = avgGrades[i];
            g = *(group+i);
        }
    }
    FILE *file = fopen("aaa.txt", "w");
    if (file != NULL) {
        for (int i = 0; i < c; i++) {
            if ((*(arrayOfStudent + i)).group != g) {
                student tmp = *(arrayOfStudent + i);
                fprintf(file, "%s\n%d\n%d\n%d\n%d\n", tmp.surname, tmp.group, tmp.grades[0], tmp.grades[1],
                        tmp.grades[2]);
            }
        }
        fclose(file);
    }
}
 
void input(){
    FILE *file = fopen("aaa.txt", "w");
    if(file != NULL){
        int n;
        printf("insert quantity students");
        scanf("%d",&n);
        for(int i = 0; i < n; i++){
            student tmp;
            printf("Input surname:");
            scanf("%20s",tmp.surname);
            printf("Input group:");
            scanf("%d", &tmp.group);
            printf("Input grades:");
            scanf("%d %d %d", tmp.grades, tmp.grades + 1, tmp.grades + 2);
            fprintf(file, "%s\n%d\n%d\n%d\n%d\n", tmp.surname, tmp.group, tmp.grades[0], tmp.grades[1], tmp.grades[2]);
        }
        fclose(file);
    }
}
 
student *readStudent(int *c){
    int key;
    FILE *file = fopen("aaa.txt", "r");
    student *result = NULL;
    if(file != NULL){
        student tmp;
        while(fscanf(file, "%20s %d %d %d %d", tmp.surname, &tmp.group, &tmp.grades[0], &tmp.grades[1], &tmp.grades[2]) != EOF){
            *c = (*(c))+ 1;
        }
        rewind(file);
        student *arrayOfStudent = (student *)malloc(sizeof(student) * *c);
        for(int i = 0; i < *c; i++){
            student temp;
            key = fscanf(file, "%20s %d %d %d %d", temp.surname, &temp.group, &temp.grades[0], &temp.grades[1], &temp.grades[2]);
            *(arrayOfStudent + i) = temp;
            if (key != 5){
                printf("\ndata crashed");
                arrayOfStudent = NULL;
                break;
            }
        }
        result = arrayOfStudent;
        fclose(file);
        if (arrayOfStudent == NULL){
            free(arrayOfStudent);
        }
    }
    return result;
}
 
void workSort(student *arrayOfStudent, int c) {
    for (int j = 0; j < c; j++) {
        for (int i = 0; i < c - 1; i++) {
            if ((*(arrayOfStudent + i)).group < (*(arrayOfStudent + i + 1)).group)
            swap(arrayOfStudent + i, arrayOfStudent + i + 1);
            else if (strcmp(arrayOfStudent[i].surname, arrayOfStudent[i + 1].surname) > 0 && ((*(arrayOfStudent + i)).group == (*(arrayOfStudent + i + 1)).group))
                swap(arrayOfStudent + i, arrayOfStudent + i + 1);
        }
    }
    FILE *file = fopen("aaa.txt", "w");
    if (file != NULL) {
        for (int i = 0; i < c; i++) {
            student tmp = *(arrayOfStudent + i);
            fprintf(file, "%s\n%d\n%d\n%d\n%d\n", tmp.surname, tmp.group, tmp.grades[0], tmp.grades[1],
                    tmp.grades[2]);
        }
        fclose(file);
    }
}
 
void swap(student *a, student *b) {
    student tmp = *a;
    *a = *b;
    *b = tmp;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://op-al.gitbook.io/s-30-voprosy-i-dop.-voprosy/16.-tekstovye-faily.-funkcii-dlya-raboty-s-tekstovymi-failami.-algoritmy-raboty-s-tekstovymi-fail.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
