C語言-文件拷貝示例

 

#define DELETE_LEN 4*1024
static const char *FILE = "/test";
static char *buf = NULL;
static int count = 0;
buf = (char *)malloc(DELETE_LEN);

res = copyFileToMem(FILE,buf,&count,DELETE_LEN);
if(res < 0) {
    printf("copyFileToMem failed\n");
}

if(buf!= NULL)
    int res = copyFileFromMem(FILE,buf,count);
    if(res < 0) {
    printf("copyFileFromMem failed\n");
}
    free(buf);
    buf= NULL;

 

static int copyFileToMem(const char *path,char *p,int *count,int size) {
    char *tmp = p;

    FILE* fd = fopen_path(path,"r");
    if(NULL == fd) {
        printf("open %s failed %d(%s)\n",path,errno,strerror(errno));
        return -1;
    }

    int res = 0;
    char buf[50] = {0};
    while((res = fread(buf,1,sizeof(buf),fd)) > 0) {
        *count += res;
        if (*count <= size) {
            memcpy(tmp,buf,res);
            tmp += res;
        } else {
            *count -= res;
            printf("size overflow");
            break;
        }
    }
    fclose(fd);

    return 0;
}

static int copyFileFromMem(const char *path,char *p,int count) {
    FILE* fd = fopen_path(path,"w+");
    if(NULL == fd) {
        printf("open %s failed %d(%s)\n",path,errno,strerror(errno));
        return -1;
    }
    int res = 0;
    if ((res = fwrite(p,1,count,fd)) > 0) {
        printf("write ok\n");
    }

    fclose(fd);

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章