Linux下文件复制

1.编程

#include
   
   
    
    
#include
    
    
     
     
#include
     
     
      
      

//功能:实现Linux下文件复制

int CopyFile(char *SourcePath,char *Path);			//复制文件函数
int GetCopyPath(char *SourcePath,char *Path,char CopyPath[]);	//获取复制路径函数

int main(int argc,char *argv[])
{
	if(argc == 1)
	{
		printf("缺少文件路径以及复制路径!\n");
		return 1;
	}
	else if(argc == 2)
	{
		printf("缺少复制路径!\n");
		return 1;
	}
	else if(argc == 3)
	{
		CopyFile(argv[1],argv[2]);			//调用复制文件函数
		return 0;
	}
}

int CopyFile(char *SourcePath,char *Path)
{
	FILE *fin = NULL;
	FILE *fout = NULL;
	char CopyPath[100];
	char ch = ' ';

	if(!(fin = fopen(SourcePath,"r")))			//以读操作打开文件
	{
		printf("文件%s读取失败!\n",SourcePath);
		return 1;
	}
	GetCopyPath(SourcePath,Path,CopyPath);			//调用获取复制路径函数,获取复制路径(带文件名)
	if(!(fout = fopen(CopyPath,"w")))			//以写操作打开文件
	{
		printf("文件%s读取失败!\n",CopyPath);
		return 1;
	}
	
	ch = fgetc(fin);					//每次读取一个字符,写入复制路径文件
	while(ch != EOF)
	{
		fputc(ch,fout);
		ch = fgetc(fin);
	}

	fclose(fin);						//关闭读操作文件
	fclose(fout);						//关闭写操作文件

	return 0;
}

int GetCopyPath(char *SourcePath,char *Path,char CopyPath[])
{
	char FileName[100];
	char ch = '/';
	int n = 0;
	int i = 0;

	n = strlen(SourcePath);
	for(i=n-1;i>=0;i--)					//对文件路径从后向前读取
	{
		if(SourcePath[i] == ch)				//读取到‘/’后截取文件名
		{
			strncpy(FileName,SourcePath+i+1,n-i-1);
			FileName[n-i-1] = '\0';
			break;
		}
	}
	if(i == -1)						//若文件路径没有‘/’,文件路径就是需要复制的文件
		strcpy(FileName,SourcePath);

	strcpy(CopyPath,Path);					//在复制路径后加上文件名
	strcat(CopyPath,"/");
	strcat(CopyPath,FileName);

	return 0;
}

     
     
    
    
   
   
2.编译

gcc CopyFile.c -o a.out
3.实现及查看


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值