保存数据到文件

//writetofile.h
#ifndef WRITE_TO_FILE_H
#define WRITE_TO_FILE_H

#ifndef WRITE_TO_FILE
    #define WRITE_TO_FILE
#endif

#ifdef WRITE_TO_FILE
    #ifdef __ANDROID__
        #define WRITE_TO_PATH "/sdcard"
    #else
        #define WRITE_TO_PATH "."
    #endif

    #include <stdio.h>
    #include <stdarg.h> //va_list
    #include <string.h> //memset

    static void WriteToFileTxt(int64_t id,const char* fname,const char* format,...){
        if(!fname || !format) {
            return;
        }
        char fname_buf[100];
        memset(fname_buf,100,0);
        snprintf(fname_buf,100,"%s/%lld_%s",WRITE_TO_PATH,id,fname);
        FILE* fp=fopen(fname_buf,"a");
        if(fp) {
            va_list args;
            va_start(args,format);
            vfprintf(fp,format,args);
            va_end(args);
            fclose(fp);
        }
        return;
    }

    static void WriteToFileBin(int64_t id,const char* fname,const char* data,int size) {
        if(!fname || !data|| size<=0) {
            return;
        }
        char fname_buf[100];
        memset(fname_buf,100,0);
        snprintf(fname_buf,100,"%s/%lld_%s",WRITE_TO_PATH,id,fname);
        FILE* fp=fopen(fname_buf,"a");
        if(fp) {
            fwrite(data,sizeof(char),size,fp);
            fclose(fp);
        }
        return;
    }
#else
    #define WriteToFileTxt
    #define WriteToFileBin
#endif

#endif
posted @ 2020-04-15 09:50  JohnRed  阅读(222)  评论(0编辑  收藏  举报