#include #include #include #include #include int fileCountLines(file_t* f) { char ch; int lines = 0; FILE* fd = fopen(f->path, "r"); while ((ch = fgetc(fd)) != EOF) { if (ch == '\n') { lines++; } } fclose(fd); return lines; } void _fileLoadLines(file_t* f, FILE* fd) { int lineLength; char ch; vector_t* line = vectorInit(CHAR); for (int i = 0; i < f->length; i++) { while ((ch = fgetc(fd)) != '\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); } } char* fileToString(file_t* f) { return (char *)vectorToString(f->lines); } file_t* fileInit(char* path) { 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); } f->path = path; FILE* fd = fopen(f->path, "r"); if (fd == NULL) { fprintf(stderr, "unable to open file %s with mode \"r\"\n", path); fclose(fd); fileCleanup(f); exit(EXIT_FAILURE); } f->length = fileCountLines(f); f->lines = vectorInit(VECTOR); // vector of vectors of chars = vector of strings _fileLoadLines(f, fd); fclose(fd); return f; } void fileCleanup(file_t* f) { vectorCleanup(f->lines); 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); } }