zoukankan      html  css  js  c++  java
  • linux系统编程:cp的另外一种实现方式

    之前,这篇文章:linux系统编程:自己动手写一个cp命令 已经实现过一个版本。

    这里再来一个版本,涉及知识点:

    linux系统编程:open常用参数详解

    Linux系统编程:简单文件IO操作

     1 /*================================================================
     2 *   Copyright (C) 2018 . All rights reserved.
     3 *   
     4 *   文件名称:cp.c
     5 *   创 建 者:ghostwu(吴华)
     6 *   创建日期:2018年01月10日
     7 *   描    述:用open和write实现cp命令
     8 *
     9 ================================================================*/
    10 
    11 #include <stdio.h>
    12 #include <sys/types.h>
    13 #include <sys/stat.h>
    14 #include <fcntl.h>
    15 #include <errno.h>
    16 #include <stdlib.h>
    17 #include <string.h>
    18 #include <unistd.h>
    19 
    20 #ifndef BUFSIZE
    21 #define BUFSIZE 1024
    22 #endif
    23 
    24 
    25 int main(int argc, char *argv[])
    26 {
    27     int input_fd, output_fd, openflags;
    28     mode_t fileperms;
    29     ssize_t num;
    30 
    31     openflags = O_WRONLY | O_CREAT | O_TRUNC;
    32     fileperms = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IXOTH;
    33 
    34     if( argc != 3 || strcmp( argv[1], "--help" ) == 0 ) {
    35         printf( "usage:%s old-file new-file
    ", argv[0] );
    36         exit( -1 );
    37     }
    38 
    39     //打开源文件
    40     input_fd = open( argv[1], O_RDONLY );
    41     if( input_fd < 0 ) {
    42         printf( "源文件%s打开失败
    ", argv[1] );
    43         exit( -1 );
    44     }
    45 
    46     //创建目标文件
    47     output_fd = open( argv[2], openflags, fileperms );
    48     if( output_fd < 0 ) {
    49         printf( "目标文件%s创建失败
    ", argv[2] );
    50         exit( -1 );
    51     }
    52 
    53     char buf[BUFSIZE];
    54 
    55     //开始读取源文件的数据,向目标文件拷贝数据
    56     while( ( num = read( input_fd, buf, BUFSIZE ) ) > 0 ) {
    57         if( write( output_fd, buf, num ) != num ) {
    58             printf( "向目标文件%s写入数据失败
    ", argv[2] );
    59             exit( -1 );
    60         }
    61     }
    62 
    63     if( num < 0 ) {
    64         printf( "读取源文件%s数据失败
    ", argv[1] );
    65         exit( -1 );
    66     }
    67 
    68     if( close( input_fd ) < 0 ) {
    69         perror( "close input_fd" );
    70         exit( -1 );
    71     }
    72     if( close( output_fd ) < 0 ) {
    73         perror( "close output_fd" );
    74         exit( -1 );
    75     }
    76 
    77     return 0;
    78 }
    View Code
  • 相关阅读:
    Android 比较好用的浏览器
    Chrome浏览器 插件
    火狐浏览器 安装网页视频下载插件(插件名称:Video DownloadHelper)
    Pandas高频使用技巧
    【Golang】关于Go中的类型转换
    基于Apache Hudi 的CDC数据入湖
    pageoffice代码优化前备份
    jnpf javacloud 微服务配置运气记录
    cAdvisor监控容器
    节点状态同步机制
  • 原文地址:https://www.cnblogs.com/ghostwu/p/8259752.html
Copyright © 2011-2022 走看看