Очередь на файле

mail@pastecode.io avatar
unknown
c_cpp
a year ago
2.6 kB
1
Indexable
Never
// queue.h
#ifndef QUEUE_H
#define QUEUE_H

#include <stdbool.h>
#include <stdio.h>

#define T int

// Очередь на файле

typedef struct {
    char* file_path; // 
    int size;
} file_queue;

void file_queue_create(file_queue* fq, char* file_path);
bool file_queue_is_empty(file_queue* fq);
void file_queue_push(file_queue* fq, T t);
void file_queue_pop(file_queue* fq);
T file_queue_top(file_queue* fq);
int file_queue_size(file_queue* fq);
void file_queue_destroy(file_queue* fq);

 
#endif /*QUEUE_H*/

// queue.c

#include "queue.h"

void file_queue_create(file_queue* fq, char* file_path) {
    fopen(file_path, "w");
    fq->size = 0;
    fq->file_path = file_path;
}

bool file_queue_is_empty(file_queue* fq) {
    return fq->size == 0;
}

void file_queue_push(file_queue* fq, T t) {
    FILE* f = fopen(fq->file_path, "a");
    fprintf(f, "%d\n", t); // Формат ввода стоит для типа int
    fq->size++;
    fclose(f);
}

void file_queue_pop(file_queue* fq) {
    FILE* queue_file = fopen(fq->file_path, "r");
    FILE* temp_file = fopen("temp", "w");
    
    T t;
    fscanf(queue_file, "%d", &t);
    for (int i = 1; i < fq->size; i++) {
        fscanf(queue_file, "%d", &t);
        fprintf(temp_file, "%d\n", t);
    }
    
    fclose(queue_file);
    fclose(temp_file);

    queue_file = fopen(fq->file_path, "w");
    temp_file = fopen("temp", "r");
    while (fscanf(temp_file, "%d", &t) != EOF) {
        fprintf(queue_file, "%d\n", t);
    }

    fclose(queue_file);
    fclose(temp_file);
    remove("temp");

    fq->size--;

}

T file_queue_top(file_queue* fq) {
    FILE* f = fopen(fq->file_path, "r");
    T t;
    fscanf(f, "%d", &t);
    fclose(f);
    return t;
}

int file_queue_size(file_queue* fq) {
    return fq->size;
}

void file_queue_destroy(file_queue* fq) {
    remove(fq->file_path);
    fq->size = 0;
    fq->file_path = NULL;
}


// main.c  (Тесты)

#include <stdio.h>
#include "queue.h"

int main() {
    file_queue fq;
    file_queue_create(&fq, "myqueue");

    file_queue_push(&fq, 31);
    T t = file_queue_top(&fq);
    printf("%d\n", t);
    file_queue_push(&fq, 21);
    file_queue_push(&fq, 11);
    file_queue_push(&fq, 11);
    file_queue_push(&fq, 11);
    printf("%d\n", file_queue_size(&fq));


    file_queue_pop(&fq);
    printf("%d\n", t);
    file_queue_pop(&fq);

    printf("%d\n", file_queue_size(&fq));

    file_queue_destroy(&fq);
}