feat: read files and split them by lines
This commit is contained in:
parent
390f2d367a
commit
4e4e7be60e
4 changed files with 70 additions and 1 deletions
16
include/file.h
Normal file
16
include/file.h
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
#ifndef FILE_H
|
||||||
|
#define FILE_H
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
char** content;
|
||||||
|
uint64_t lines;
|
||||||
|
} File;
|
||||||
|
|
||||||
|
File* new_file(const char*);
|
||||||
|
|
||||||
|
#endif // FILE_H
|
||||||
|
|
@ -1,5 +1,9 @@
|
||||||
#ifndef MYERS_H
|
#ifndef MYERS_H
|
||||||
#define MYERS_H
|
#define MYERS_H
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include "action_list.h"
|
||||||
|
|
||||||
|
ActionList* myers_diff(char**, char**, uint64_t, uint64_t);
|
||||||
|
|
||||||
#endif // MYERS_H
|
#endif // MYERS_H
|
||||||
|
|
|
||||||
47
src/file.c
Normal file
47
src/file.c
Normal 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;
|
||||||
|
}
|
||||||
|
|
@ -1,3 +1,5 @@
|
||||||
#include "myers.h"
|
#include "myers.h"
|
||||||
|
|
||||||
|
ActionList* myers_diff(char** file1, char** file2, uint64_t offset1, uint64_t offset2) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue