预览加载中,请您耐心等待几秒...
1/10
2/10
3/10
4/10
5/10
6/10
7/10
8/10
9/10
10/10

亲,该文档总共11页,到这已经超出免费预览范围,如果喜欢就直接下载吧~

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

linuxcp命令简单的实现实现功能:$./cp~/filename~/OtherName//文件到文件的拷贝$./cp~/directory/filename.//文件到当前目录的拷贝$./cp~/directory/filename~/directory///文件到目录的拷贝不白费口舌,直接上代码才是王道!001#include002#include003#include004#include005#include006#include007#include008#include009010#defineBUF_SIZE1024011#definePATH_LEN128012013voidmy_err(char*err_string,intline)014{015fprintf(stderr,"line:%d",line);016perror(err_string);017exit(1);018}019020voidcopy_data(constintfrd,constintfwd)021{022intread_len=0,write_len=0;023unsignedcharbuf[BUF_SIZE],*p_buf;024025while((read_len=read(frd,buf,BUF_SIZE))){026027if(-1==read_len){028my_err("Readerror",__LINE__);029}030elseif(read_len>0){//把读取部分写入目标文件031p_buf=buf;032while((write_len=write(fwd,p_buf,read_len))){033if(write_len==read_len){034break;035}036elseif(write_len>0){//只写入部分037p_buf+=write_len;038read_len-=write_len;039}040elseif(-1==write_len){041my_err("Writeerror",__LINE__);042}043}044if(-1==write_len)break;045}046}047}048049intmain(intargc,char**argv)050{051052intfrd,fwd;//读写文件描述符053intlen=0;054char*pSrc,*pDes;//分别指向源文件路径和目标文件路径055structstatsrc_st,des_st;056057if(argc058printf("用法./MyCp\n");059my_err("argumentserror",__LINE__);060}061062frd=open(argv[1],O_RDONLY);063if(frd==-1){064my_err("Cannotopnefile",__LINE__);065}066067if(fstat(frd,&src_st)==-1){068my_err("staterror",__LINE__);069}070/*检查源文件路径是否是目录*/071if(S_ISDIR(src_st.st_mode)){072my_err("略过目录",__LINE__);073}074075pDes=argv[2];076stat(argv[2],&des_st);077if(S_ISDIR(des_st.st_mode)){//目标路径是目录,则使用源文件的文件名078079len=strlen(argv[1]);080pSrc=argv[1]+(len-1);//指向最后一个字符081/*先找出源文件的文件名*/082while(pSrc>=argv[1]&&*pSrc!='/'){083pSrc--;084}085pSrc++;//指向源文件名086087len=strlen(argv[2]);088//.表示复制到当前工作目录089if(1==len&&'.'==*(argv[2])){090len=0;//没有申请空间,后面就不用释放091pDes=pSrc;092}093else{//复制到某目录下,使用源文件名094pDes=(char*)malloc(sizeof(char)*PATH_LEN);095if(NULL==pDes){096my_err("mallocerror",__LINE__);097}098099strcpy(pDes,argv[2]);100101if(*(pDes+(len-1))!='/'){//目录缺少最后的'/',则补上’/‘102strcat(pDes,"/");103}104strcat(pDes+len,p