cp文件和mkstemp

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
char _tmp_path[1024];
char _config_dirpath[1024];
char _so_path[1024];
char _config_filepath[1024];
int main(){
    snprintf(_config_dirpath, sizeof(_config_dirpath), 
             "/data/c/file");
    snprintf(_so_path, sizeof(_so_path),                                                                                                                         
             "%s/libprocess.so", _config_dirpath);
    snprintf(_tmp_path, sizeof(_tmp_path),
            "%s/libprocess.XXXXXX", _config_dirpath);
    int ret = mkstemp(_tmp_path);
    if (ret == -1)
    {
        printf("create tmp so file %s fail, error:%s",
                _tmp_path, strerror(errno));
        return 1;
    }

    /* copy file to tmpfile */
    if(!copy_file(_so_path, _tmp_path))
    {
        printf("copy %s to %s so fail",
                _so_path, _tmp_path);
        return 1;
    }
    return 0; 
}
int copy_file(const char* source, const char* dst){
    int rfd = open(source, O_RDONLY);
    if (rfd == -1)
    {
        printf("%s so file open fail,error:%s", source, strerror(errno));
        return 1;
    }

    int wfd = open(dst, O_WRONLY|O_CREAT|O_APPEND);
    if (wfd == -1)
    {
        printf("%s so file open fail,error:%s", dst, strerror(errno));
        return 1;
    }
    char buf[1024];
    int rcount;
    int wcount;
    while ((rcount = read(rfd, buf, sizeof(buf))) != 0)
    {
        if (rcount == -1)
        {
            printf("read %s so file fail,error:%s", source, strerror(errno));
            return 1;
        }

        wcount = write(wfd, buf, rcount);
        if (wcount != rcount)
        {
            printf("write %s so file fail", dst);
            return 1;
        }
    }

    close(rfd);
    close(wfd);
    return 0;
}

你可能感兴趣的:(c)