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;
}
gcc CopyFile.c -o a.out