cp命令的基本用法: cp 源文件 目标文件
如果目标文件不存在 就创建, 如果存在就覆盖
实现一个cp命令其实就是读写文件的操作:
对于源文件: 把内容全部读取到缓存中,用到的函数read
对于目标文件: 把缓存中的内容全部写入到目标文件,用到的函数creat
/*================================================================
* Copyright (C) 2018 . All rights reserved.
*
* 文件名称:mycp.c
* 创 建 者:ghostwu(吴华)
* 创建日期:2018年01月08日
* 描 述:cp命令编写
*
================================================================*/ #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h> #define COPYMODE 0644
#define BUF 4096 int main(int argc, char *argv[])
{
if ( argc != ){
printf( "usage:%s source destination\n", argv[] );
exit( - );
} int in_fd = -, out_fd = -; if( ( in_fd = open( argv[], O_RDONLY ) ) == - ) {
perror( "file open" );
exit( - );
} if ( ( out_fd = creat( argv[], COPYMODE ) ) == - ) {
perror( "file copy" );
exit( - );
} char n_chars[BUF];
int len = ; while( ( len = read( in_fd, n_chars, sizeof( n_chars ) ) ) > ) {
if ( write( out_fd, n_chars, len ) != len ) {
printf( "文件:%s发生copy错误\n", argv[] );
exit( - );
}
}
if( len == - ) {
printf( "读取%s文件错误\n", argv[] );
exit( - );
} if( close( in_fd ) == - ) {
printf( "文件%s关闭失败\n", argv[] );
exit( - );
}
if( close( out_fd ) == - ) {
printf( "文件%s关闭失败\n", argv[] );
exit( - );
} return ;
}