From 4e4e7be60ed2065f40ec21ddafa3235d57fa676b Mon Sep 17 00:00:00 2001 From: lisk77 Date: Sat, 16 Aug 2025 08:16:04 +0200 Subject: [PATCH] feat: read files and split them by lines --- include/file.h | 16 ++++++++++++++++ include/myers.h | 4 ++++ src/file.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/myers.c | 4 +++- 4 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 include/file.h create mode 100644 src/file.c diff --git a/include/file.h b/include/file.h new file mode 100644 index 0000000..405e18d --- /dev/null +++ b/include/file.h @@ -0,0 +1,16 @@ +#ifndef FILE_H +#define FILE_H + +#include +#include +#include +#include + +typedef struct { + char** content; + uint64_t lines; +} File; + +File* new_file(const char*); + +#endif // FILE_H diff --git a/include/myers.h b/include/myers.h index 1ad7dee..563795a 100644 --- a/include/myers.h +++ b/include/myers.h @@ -1,5 +1,9 @@ #ifndef MYERS_H #define MYERS_H +#include +#include "action_list.h" + +ActionList* myers_diff(char**, char**, uint64_t, uint64_t); #endif // MYERS_H diff --git a/src/file.c b/src/file.c new file mode 100644 index 0000000..b442f46 --- /dev/null +++ b/src/file.c @@ -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; +} diff --git a/src/myers.c b/src/myers.c index 37e8fa2..2d9ab15 100644 --- a/src/myers.c +++ b/src/myers.c @@ -1,3 +1,5 @@ #include "myers.h" - +ActionList* myers_diff(char** file1, char** file2, uint64_t offset1, uint64_t offset2) { + return NULL; +}