cp文件和mkstemp

本文详细介绍了在程序开发中使用C语言进行文件路径设置、文件创建与复制的基本操作,包括目录路径设置、文件路径生成、临时文件创建以及文件复制实现。

#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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值