X-Git-Url: https://git.wpitchoune.net/gitweb/?a=blobdiff_plain;f=src%2Fio.c;h=f6d87542c281da082b8b49b70e8440ecc8ba55cd;hb=301be453975067183367ea8c29069476bf1b45ff;hp=cb73dcc88cb9deda349c88a0e3496ce32f16a23c;hpb=c32ae4d8a044e8444d0c132e5ea6e3b5b9230198;p=ppastats.git diff --git a/src/io.c b/src/io.c index cb73dcc..f6d8754 100644 --- a/src/io.c +++ b/src/io.c @@ -27,7 +27,7 @@ /* Directory separator is \ when cross-compiling for MS Windows systems */ #if defined(__MINGW32__) -#define DIRSEP '\\' +#define DIRSEP ('\\') #else #define DIRSEP '/' #endif @@ -118,3 +118,74 @@ void mkdirs(const char *dirs, mode_t mode) free(dir); } + +static int is_file(const char *path) +{ + struct stat st; + + int ret = lstat(path, &st); + + if (ret == 0 && S_ISREG(st.st_mode)) + return 1; + + return 0; +} + +static long file_get_size(const char *path) +{ + FILE *fp; + + if (!is_file(path)) + return -1; + + fp = fopen(path, "rb"); + if (fp) { + long size; + + if (fseek(fp, 0, SEEK_END) == -1) + return -1; + + size = ftell(fp); + + fclose(fp); + + return size; + } + + return -1; +} + +char *file_get_content(const char *fpath) +{ + long size; + + char *page; + + size = file_get_size(fpath); + if (size == -1) { + page = NULL; + + } else if (size == 0) { + page = malloc(1); + *page = '\0'; + + } else { + FILE *fp = fopen(fpath, "rb"); + if (fp) { + page = malloc(size + 1); + if (!page || size != fread(page, 1, size, fp)) { + free(page); + return NULL; + } + + *(page + size) = '\0'; + + fclose(fp); + } else { + page = NULL; + } + } + + return page; +} +