#include #include #include "file.h" #include "elog.h" #if 1 #define LOGE log_e #define LOGW log_w #define LOGD log_d #else #define LOGD printf #define LOGW printf #define LOGE printf #endif int file_length(char* path) { int r; struct stat st; r = stat(path, &st); if (r) { return -1; } return st.st_size; } int file_exist(char* path) { int r; struct stat st; r = stat(path, &st); if (r) { return 0; } return 1; } int file_save(char *path, void *buf, int len) { int r; FILE *fp; fp = fopen(path, "w"); if(!fp) { LOGE("file_save, fopen %s failed\n", path); return -1; } r = fwrite(buf, 1, len, fp); if(r!=len) { LOGE("file_save %s failed, %d, %d\n", path, r, len); r = -1; } else { r = 0; } fclose(fp); return r; } int file_load(char* path, buf_t *fbuf) { int r,flen,blen; FILE* fp; flen = file_length(path); if(flen<=0) { LOGE("____ file_load, %s failed\n", path); return -1; } blen = flen+1; fbuf->buf = (char*)malloc(blen); if(!fbuf->buf) { LOGE("____ file_load, %s malloc %d failed\n", path, flen); return -1; } fbuf->dlen = flen; fbuf->blen = blen; fp = fopen(path, "r"); if (!fp) { LOGE("file_load, fopen %s failed\n", path);; free(fbuf->buf); return -1; } r = fread(fbuf->buf, 1, flen, fp); if (r != flen) { LOGE("file_load %s failed, %d, %d\n", path, r, flen); fclose(fp); free(fbuf->buf); r = -1; } else { fbuf->buf[flen] = 0; r = 0; } fclose(fp); return r; } char* file_load2(char* path, int add0) { FILE* fp=NULL; int r,flen,blen; char *fbuf=NULL; flen = file_length(path); if(flen<=0) { LOGE("____ file_load2, %s failed\n", path); return NULL; } blen = flen+(add0?1:0); fbuf = (char*)malloc(blen); if(!fbuf) { LOGE("____ file_load2, %s malloc %d failed\n", path, flen); return NULL; } fp = fopen(path, "r"); if (!fp) { LOGE("file_load2, fopen %s failed\n", path);; free(fbuf); return NULL; } r = fread(fbuf, 1, flen, fp); if (r != flen) { LOGE("file_load2 %s failed, %d, %d\n", path, r, flen); fclose(fp); free(fbuf); fbuf = NULL; } if(add0) fbuf[flen] = 0; fclose(fp); return fbuf; } int file_copy(char *dst, char *src) { int r; buf_t fbuf; remove(dst); r = file_load(src, &fbuf); if(r==0) { r = file_save(dst, fbuf.buf, fbuf.dlen); free(fbuf.buf); } return r; } int file_remove(char *path) { return remove(path); } int file_append(char *path, void *data, int datalen) { int r=-1; FILE* fp; fp = fopen(path, "a"); if(!fp) { LOGE("file_append, fopen %s failed\n", path); return -1; } r = fwrite(data, 1, datalen, fp); if(r==datalen) { r = 0; } else { LOGE("file_append %s failed, %d, %d\n", path, r, datalen); r = -1; } fclose(fp); return r; }