Linux 用代码实现整个目录复制

用c实现不用命令实现整个文件目录复制:

#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <dirent.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>



int cpy(char *pathname,char *pathname2)
{
	int o_fd,o_fd1;
    o_fd=open(pathname,O_RDWR);//原目录
    o_fd1=open(pathname2,O_RDWR|O_CREAT);//复制目标
    if (o_fd==-1||o_fd1==-1)
    {
        printf("打开失败1\n");
    }
   
    char buf[10]={0};
    int n,u=0;
    while(1)
    {
        n=read(o_fd,buf,sizeof(buf)); //读写
        write(o_fd1,buf,sizeof(buf));
        if(n==0)//判断是否读完
        {
            break;
        }
        u+=10;
        
    }
    close(o_fd);
    close(o_fd1);
   
    return 0;
}

void dir_func(char *pathname,char *pathname2);
int main(int argc, char const *argv[])
{
	char a[10],b[10];
	sprintf(a,"%s",argv[1]);
	sprintf(b,"%s",argv[2]);
	mkdir(b,0777);
	dir_func(a,b);
	printf("复制成功");
	return 0;
}
void dir_func(char *pathname,char *pathname2)
{
	//打开目录
	DIR *dir=opendir(pathname);
	//定义目录项结构体指针
	struct dirent *buf=NULL;
	char s[20],s1[20];
	while(1)
	{

		//读取目录指针到结构体里面去
		buf=readdir(dir);
		if (buf==NULL)
			{
				break;
			}
		if (buf->d_type==8) //普通文件
		{
        	sprintf(s,"%s/%s",pathname,buf->d_name );
			sprintf(s1,"%s/%s",pathname2,buf->d_name);
			cpy(s,s1);

		}
		else if (buf->d_type==4)//判断是不是目录
		{			
			if (buf->d_name[0]=='.')
			{
				continue;
			}
			sprintf(s,"%s/%s",pathname,buf->d_name );
			sprintf(s1,"%s/%s",pathname2,buf->d_name );
			mkdir(s1,0777);
			dir_func(s,s1);
		}	
	}
	
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值