feat: read files and split them by lines

This commit is contained in:
lisk77 2025-08-16 08:16:04 +02:00
parent 390f2d367a
commit 4e4e7be60e
4 changed files with 70 additions and 1 deletions

47
src/file.c Normal file
View file

@ -0,0 +1,47 @@
#include "file.h"
File* new_file(const char* path) {
if (!path) return NULL;
FILE* f = fopen(path, "rb");
if (!f) return NULL;
if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
long sz = ftell(f);
if (sz < 0) { fclose(f); return NULL; }
if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
size_t n = (size_t)sz;
char* buf = (char *)calloc(n + 1, 1);
if (!buf) { fclose(f); return NULL; }
size_t got = fread(buf, 1, n, f);
fclose(f);
buf[got] = '\0';
size_t count = 1;
for (size_t i = 0; i < got; ++i) if (buf[i] == '\n') count++;
if (buf[got-1] == '\n') count--;
char** lines = count ? (char**)malloc(count * sizeof *lines) : NULL;
if (count && !lines) return NULL;
size_t idx = 0;
lines[idx++] = buf;
for (size_t i = 0; i < got; ++i) {
if (buf[i] == '\n') {
if (i > 0 && buf[i-1] == '\r') buf[i-1] = '\0';
buf[i] = '\0';
if (i+1 < got) lines[idx++] = &buf[i+1];
}
}
if (got > 0 && buf[got-1] == '\r') buf[got-1] = '\0';
File* file = calloc(1, sizeof(File));
file->content = lines;
file->lines = idx;
return file;
}