initial commit

This commit is contained in:
Odweta
2023-12-07 20:03:18 +01:00
commit 7fb1267224
8 changed files with 722 additions and 0 deletions
+105
View File
@@ -0,0 +1,105 @@
#include <odweta/file.h>
#include <odweta/vector.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int
fileCountLines(file_t* f) {
char ch;
int lines = 0;
while ((ch = fgetc(f->descriptor)) != EOF) {
if (ch == '\n') {
lines++;
}
}
rewind(f->descriptor);
return lines;
}
void
_fileLoadLines(file_t* f) {
int lineLength;
char ch;
vector_t* line = vectorInit(CHAR);
for (int i = 0; i < f->length; i++) {
while ((ch = fgetc(f->descriptor)) != '\n' && ch != EOF) {
vectorPush(line, &ch);
}
// Skip the newline character if it exists
if (ch == '\n') {
char* empty = "";
vectorPush(line, empty);
}
vectorPush(f->lines, line);
line = vectorInit(CHAR);
}
rewind(f->descriptor);
}
char*
fileToString(file_t* f) {
return (char *)vectorToString(f->lines);
}
file_t*
fileInit(char* path, char* mode) {
file_t* f = malloc(sizeof(file_t));
if (f == NULL) {
perror("failed to allocate memory for the file\n");
exit(EXIT_FAILURE);
}
f->lines = malloc(sizeof(vector_t));
if (f->lines == NULL) {
perror("failed to allocate memory for the file contents vector\n");
exit(EXIT_FAILURE);
}
int imode = 0;
if (strcmp(mode, "r") == 0) {
imode = 0;
} else if (strcmp(mode, "w") == 0) {
imode = 1;
} else if (strcmp(mode, "a") == 0) {
imode = 2;
} else {
perror("only allowed modes for file opening are \"r\", \"w\" and \"a\"\n");
exit(EXIT_FAILURE);
}
f->descriptor = fopen(path, mode);
if (f->descriptor == NULL) {
fprintf(stderr, "unable to open file %s with mode %s\n", path, mode);
fileCleanup(f);
exit(EXIT_FAILURE);
}
f->length = fileCountLines(f);
f->lines = vectorInit(VECTOR); // vector of vectors of chars = vector of strings
if (imode == 0) _fileLoadLines(f);
return f;
}
void
fileCleanup(file_t* f) {
vectorCleanup(f->lines);
fclose(f->descriptor);
free(f);
}
void
filePrint(file_t* f) {
vector_t* line = vectorInit(CHAR);
for (int i = 0; i < f->length; i++) {
line = (vector_t *)vectorGetAt(f->lines, i);
vectorPrintAsString(line);
}
}