#include "buffer.h" #include #include #include #include static int file_read( char** text, size_t* text_capacity, size_t* text_length, const char* path) { FILE* file = fopen(path, "r"); if (!file) { fprintf(stderr, "error: could not open file '%s'\n", path); return -1; } fseek(file, 0, SEEK_END); size_t file_size = (size_t)ftell(file); rewind(file); size_t initial_capacity = 8; while (initial_capacity < file_size + 1) initial_capacity *= 2; *text = calloc(initial_capacity, sizeof(char)); *text_capacity = initial_capacity; *text_length = file_size; size_t bytes_read = fread(*text, sizeof(char), file_size, file); if (bytes_read != file_size) { fprintf(stderr, "error: could not read file '%s'\n", path); return -1; } return 0; } void buffer_init(Buffer* buffer) { const size_t text_initial_capacity = 8; *buffer = (Buffer) { .path = nullptr, .text = calloc(1, text_initial_capacity), .text_capacity = text_initial_capacity, .text_length = 0, .changed = false, }; } int buffer_from_file(Buffer* buffer, const char* path) { *buffer = (Buffer) { .path = strdup(path), .text = nullptr, .text_capacity = 0, .text_length = 0, .changed = false, }; int status = file_read( &buffer->text, &buffer->text_capacity, &buffer->text_length, path); return status; } void buffer_deinit(Buffer* buffer) { if (buffer->path) free(buffer->path); free(buffer->text); }