mycopy.c

来自「LINUX下文件拷贝,实现文件目录拷贝,包括文件和文件目录」· C语言 代码 · 共 68 行

C
68
字号
#include "dirent.h"
#include "sys/stat.h"
#include "time.h"
#include "stdio.h"
#include "fcntl.h"
#include "string.h"
#define PERM 0644


int CopyDir(char *srcPath,char *aimPath)
{
	char buf[BUFSIZ];
	struct dirent *direntp;
	DIR *dirp;
	struct stat statbuf;
    int bytes;
	int fromfd,tofd,n;
	if((dirp = opendir(srcPath)) == NULL)
	{
        printf("Failed to open directory!\n");
		return 0;
	}
	while((direntp = readdir(dirp)) != NULL)
	{
		printf("%s\n",direntp->d_name);
		strcat(srcPath,direntp->d_name);
		strcat(aimPath,direntp->d_name);
		if(stat(srcPath,&statbuf) == -1)
		{
			if((fromfd = open(srcPath,0)) == -1)
			{
				printf("Failed to open input file!\n");
				return 0;
			}
			if((tofd = creat(aimPath,PERM)) == -1)
			{
				printf("Failed to create output file!\n");
				return 0;
			}		       

          while ((n=read(fromfd,buf,BUFSIZ))>0)
			if (write(tofd,buf,n)!=n)
			printf("write error",(char *)0);
   		close(fromfd);
   		close(tofd);
			printf("copied from %s to %s\n",srcPath,aimPath);
			return 1;
		}
		else
		{
			CopyDir(srcPath,aimPath);
		}
	}
}
int main(int argc,char* argv[])
{
	
	if(argc != 3)
	{
		printf("directory error!\n");
		return 0;
	}
	
    CopyDir(argv[1],argv[2]);
	return 1;

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?