Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //plainTextHandle.h
- #include <stdio.>
- #include <stdlib.>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- typedef struct {
- unsigned int textLen; //Length of actual file, Excluding terminating \0
- char* textContent; //Pointer to memory containing the actual text file
- int textIndexCount; //Number of lines
- char** textIndex; //Pointer to list of pointers to the beginning of each null-terminated line
- } t_textFile;
- t_textFile* t_textFile_C(FILE* stream);
- void t_textFile_D(t_textFile* target);
- //plainTextHandle.c
- #include "plainTextHandle.h"
- t_textFile* t_textFile_C(FILE* stream) {
- t_textFile* newStruct = malloc(sizeof(*newStruct));
- //Determine File Length
- struct stat statBuff;
- if(fstat(fileno(stream), &statBuff)) { free(newStruct); return(0); }
- newStruct->textLen = statBuff.st_size;
- //Buffer
- newStruct->textContent = malloc(newStruct->textLen+1);
- //Load
- if( newStruct->textLen != fread(newStruct->textContent, 1, newStruct->textLen, stream) ) {
- //Some error occurred, end of file was not reached
- if(DEBUG_MODE){printf("Failed to read file");}
- free(newStruct->textContent);
- free(newStruct);
- return(0);
- }
- //Null Terminate
- newStruct->textContent[newStruct->textLen] = '\0';
- //Get count of lines
- newStruct->textIndexCount = 1;
- for(unsigned int i=1; i < newStruct->textLen; i++){
- if(newStruct->textContent[i] == '\n') {
- (newStruct->textIndexCount)++;
- }
- }
- //Buffer for line index
- newStruct->textIndex = malloc(sizeof(newStruct->textIndex) * newStruct->textIndexCount);
- //Populate index, replace \n with \0 to null-terminate each line
- newStruct->textIndex[0] = newStruct->textContent; //First line
- int j = 1; //Position in the index
- for(unsigned int i=1; i < newStruct->textLen; i++){
- if(newStruct->textContent[i] == '\n') {
- newStruct->textContent[i] = '\0';
- newStruct->textIndex[j] = newStruct->textContent+i+1;
- j++;
- }
- }
- return(newStruct);
- }
- void t_textFile_D(t_textFile* target) {
- free(target->textIndex);
- target->textIndex = 0;
- free(target->textContent);
- target->textContent = 0;
- free(target);
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement