点击(此处)折叠或打开
-
/*cp命令简单实现
-
*cp src dest
-
*支持 -i选项 cp -i src dest
-
*-i 询问是否覆盖,当src dest相同时
-
*/
-
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<fcntl.h>
-
#include<unistd.h>
-
-
#define BUFFSIZE 4096
-
#define COPYMODE 0644
-
-
void usage(void);
-
int file_exits(char *filename); //文件存在返回1,失败返回0
-
int file_replace(char *filename);
-
-
int main(int argc,char *argv[])
-
{
-
char *src = NULL,*dest = NULL;
-
char buff[BUFFSIZE];
-
int i_option = 0;
-
int in_fd,out_fd;
-
int n_chars;
-
-
while(--argc) //处理参数
-
{
-
if( strcmp("-i",*++argv) == 0 )
-
i_option = 1;
-
else if( !src )
-
src = *argv;
-
else if( !dest )
-
dest = *argv;
-
else
-
usage(); //打印使用方法并退出
-
}
-
if( !src || !dest )
-
usage();
-
-
if( (in_fd = open(src,O_RDONLY)) == -1 ) //打开源文件
-
{
-
perror("open src file failed");
-
exit(1);
-
}
-
-
if( !i_option || !file_exits(dest) || file_replace(dest) ) //目标文件
-
{ //创建一个文件并以只写的方式打开,如果原来该文件存在,会将这个文件的长度截短为0
-
if( (out_fd = creat(dest,COPYMODE)) == -1 )
-
{
-
perror("creat dest failed");
-
exit(1);
-
}
-
}
-
-
while( (n_chars = read(in_fd,buff,BUFFSIZE)) > 0 )
-
{
-
if( write(out_fd,buff,n_chars) != n_chars )
-
{
-
perror("write to dest file failed");
-
exit(1);
-
}
-
}
-
if( n_chars < 0 )
-
{
-
perror("read from src file failed");
-
exit(1);
-
}
-
-
close(in_fd);
-
close(out_fd);
-
-
return 0;
-
}
-
-
int file_exits(char *filename) //文件存在返回1,失败返回0
-
{
-
int fd;
-
fd = open(filename,O_RDONLY);
-
if(fd == -1)
-
return 0;
-
else
-
{
-
if( close(fd) == -1 )
-
{
-
perror("close file failed");
-
exit(1);
-
}
-
return 1;
-
}
-
}
-
-
int file_replace(char *filename)
-
{
-
char ans[10];
-
int retval = 0;
-
int ch;
-
-
fprintf(stderr,"replace the %s ?",filename);
-
if( scanf("%9s",ans) == 1 )
-
{
-
if( ans[0] == 'Y' || ans[0] == 'y' )
-
retval = 1;
-
}
-
while( (ch=getchar()) != EOF && ch != '\n' )
-
continue;
-
return retval;
-
}
-
-
void usage(void)
-
{
-
printf("usage:cp [-i] src dest\n");
-
exit(1);
- }