linux gnu c 复制文件实例(open,close,creat,read,write)

linux使用open,close,creat,read,write库函数实现文件复制的实例代码如下:

#include <unistd.h>
#include<fcntl.h>
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>

// 复制文件,成功返回0,失败返回-1
int copy_file(const char* src_path,const char* dst_path)
{
	if(src_path && dst_path){
		int in,out;
		ssize_t size;
		// TLS变量,减少堆栈占用
		static __thread char buffer[512];
		// 内置函数(nested function),用于函数返回时关闭in,out文件句柄
		int do_return(int code){
			if(-1 == code){
				perror(strerror(errno));
			}
			if(in)
				close(in);
			if(out)
				close(out);
			return code;
		}
		in=open(src_path,O_RDONLY);
		if(-1==in)
		{
			return do_return(-1);
		}
		//S_IRUSR(S_IREAD)	文件拥有者具备读权限
		//S_IWUSR(S_IWRITE)	文件拥有者具备写权限
		//S_IRGRP	用户组具备读权限
		//S_IWGRP	用户组具备写权限
		//S_IXGRP	用户组具备可执行权限
		//S_IROTH	其他用户具备读权限
		// 创建目标文件,并指定合适的权限
		const __mode_t mode = S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH;
		out=creat(dst_path,mode);
		if(-1==out)
		{
			return do_return(-1);
		}
		while(1)
		{
			size=read(in,buffer,sizeof(buffer));
			if(size>0){
				if(-1 == write(out,buffer,size)){
					return do_return(-1);
				}
			}else if (0 == size){
				break;
			}else if( -1 == size){
				return do_return(-1);
			}
		}
		{
			// 如果目标文件权限与所要求的权限不同则修改文件权限
			struct stat s_buf;
			stat(dst_path,&s_buf);
			if(mode != (s_buf.st_mode & mode)){
				if(-1 == chmod(dst_path,mode)){
					return do_return(-1);
				}
			}
		}
		return do_return(0);
	}
	return -1;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

10km

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值