资源简介
linux新手区:www.edsionte.com
本程序使用linux下C语言实现linux系统中常用的CP命令。本程序使用linux下C语言实现linux系统中常用的CP命令。本程序使用linux下C语言实现linux系统中常用的CP命令。本程序使用linux下C语言实现linux系统中常用的CP命令。
代码片段和文件信息
/*
code by edsionte
www.edsionte.com
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int param_r;
void cp_single(char *original_src_pathchar* original_dest_path)
{
struct stat buf;
int len;
char ch[10]filename[PATH_MAX+1]dest_dir[PATH_MAX+1];
int fdrdfdwtijk;
char src_path[PATH_MAX+1]dest_path[PATH_MAX+1];
strcpy(src_pathoriginal_src_path);
strcpy(dest_pathoriginal_dest_path);
for(k=0;k {
if(src_path[k]==‘/‘)
break;
}
char temp_path[PATH_MAX+1]=“./“;
if(k==strlen(src_path))
{
strcat(temp_pathsrc_path);
strcpy(src_pathtemp_path);
}
//extract the file name from src_path
for(i=strlen(src_path)-1;i>0;i--)
{
if(src_path[i]==‘/‘)
break;
}
j=k=0;
for(j=i;j {
filename[k++]=src_path[j];
}
filename[k]=‘\0‘;
//check the if dest path has exsited
if(stat(dest_path&buf)==0)
{
//the dest_path exsited
if(S_ISDIR(buf.st_mode))
{
if(dest_path[strlen(dest_path)-1]==‘/‘)
dest_path[strlen(dest_path)-1]=‘\0‘;
strcat(dest_pathfilename);
}
/*
if the path is not a directory and it means that the file has existed.
copying the src file to this exist file will cover the current content.
*/
}
else
{
/*
this code is not exact
it can not check the legality of the directory
such as “~/existdirectory/nothisdirectory/nothisfile“
*/
/*
if(dest_path[strlen(dest_path)-1]==‘/‘)
{
printf(“my_cp:can‘t create the file:\“%s\“:it is a directory.\n“dest_path);
exit(1);
}
*/
//the dest_path didn‘t exsit
for(i=strlen(dest_path)-1;i>=0;i--)
{
if(dest_path[i]==‘/‘)
break;
}
if(i>=0)
{
strncpy(dest_dirdest_pathi+1);
if(stat(dest_dir&buf)==-1)
{
printf(“my_cp:accessing:\“%s\“ :it is‘t a directory.\n“dest_path);
exit(1);
}
}
}
//fistly the content which was read from srouce file will be write to dest file
if((fdrd=open(src_pathO_RDONLY))==-1)
{
perror(“open“);
exit(1);
}
if(lseek(fdrd0SEEK_END)==-1)
{
perror(“lseek“);
exit(1);
}
if((len=lseek(fdrd0SEEK_CUR))==-1)
{
perror(“lseek“);
exit(1);
}
if(lseek(fdrd0SEEK_SET)==-1)
{
perror(“lseek“);
exit(1);
}
//open the dest file
if((fdwt=open(dest_pathO_CREAT|O_TRUNC|O_RDWRS_IRWXU))==-1)
{
perror(“open“);
exit(1);
}
close(fdwt);
if((fdwt=open(dest_pathO_WRONLY|O_APPEND))==-1)
{
perror(“open“);
exit(1);
}
while(len-->0)
{
//write all characters to dest file
if(read(fdrdch1)!=1)
{
perror(“read“);
exit(1);
}
if(write(fdwtch1)!=1)
{
perror(“write“);
exit(1);
}
}
//get src file‘s attributes
if(fstat(fdrd&buf)==-1)
{
perror(“fstat“);
exit(1);
}
评论
共有 条评论