X-Git-Url: http://git.wpitchoune.net/gitweb/?a=blobdiff_plain;f=src%2Fio.c;h=908e8fe485714ca1756da51f9d37c46fa4f95b20;hb=1378a843b2e5ce3fbc4429b07844cc37d42e0d8e;hp=aeeed8c962c3f9e8c57f29fa57d93b461f18d6f8;hpb=df19eac22b08c4793607679e2ea471ae64b824fd;p=ppastats.git diff --git a/src/io.c b/src/io.c index aeeed8c..908e8fe 100644 --- a/src/io.c +++ b/src/io.c @@ -1,11 +1,11 @@ /* - * Copyright (C) 2011 jeanfi@gmail.com + * Copyright (C) 2011-2014 jeanfi@gmail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. - + * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU @@ -20,9 +20,18 @@ #include #include #include +#include #include "io.h" +/* Directory separator is \ when cross-compiling for MS Windows + systems */ +#if defined(__MINGW32__) +#define DIRSEP ('\\') +#else +#define DIRSEP '/' +#endif + #define FCOPY_BUF_SZ 4096 static int file_copy(FILE *src, FILE *dst) @@ -88,3 +97,95 @@ char *path_append(const char *odir, const char *name) return dir; } +void mkdirs(const char *dirs, mode_t mode) +{ + char *c = (char *)dirs; + char *dir = malloc(strlen(dirs) + 1); + + int i = 0; + while (*c) { + if ((*c == DIRSEP || *c == '\0') && c != dirs) { + strncpy(dir, dirs, i); + dir[i] = '\0'; + mkdir(dir, mode); + } + + c++; + i++; + } + + mkdir(dirs, 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; +} +