Skip to content

Instantly share code, notes, and snippets.

@alsamitech
Created August 24, 2021 15:19
Show Gist options
  • Save alsamitech/70a60fa5da72e16d3eeaf43521d08178 to your computer and use it in GitHub Desktop.
Save alsamitech/70a60fa5da72e16d3eeaf43521d08178 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <memory.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
struct heap_str{
size_t heap_sz;
size_t len;
char* str;
};
typedef struct heap_str heap_str_t;
heap_str_t heap_str_init(const size_t init_sz){
heap_str_t heap_str={init_sz, 0, (char*)malloc(init_sz)};
return heap_str;
}
_Bool unix_read_file(heap_str_t* const restrict heap_str,const char* filenm){
int fd=open(filenm, O_RDONLY);
if(fd>0){
struct stat stats;
fstat(fd, &stats);
heap_str->len=stats.st_size;
if(stats.st_size>heap_str->heap_sz){
heap_str->str=(char*)realloc(heap_str->str, (heap_str->heap_sz=stats.st_size));
}
read(fd, heap_str->str, stats.st_size);
close(fd);
}else return 0;
return 1;
}
_Bool read_text_file(heap_str_t* const restrict heap_str, const char* filenm){
FILE* const f=fopen(filenm, "r");
if(f){
fseek(f, 0, SEEK_END);
heap_str->len=ftell(f);
fseek(f, 0, SEEK_SET);
if(heap_str->len>heap_str->heap_sz)
heap_str->str=(char*)realloc(heap_str->str,(heap_str->heap_sz=heap_str->len));
fread(heap_str->str,1, heap_str->len, f);
fclose(f);
}else return 0;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment