Linux C编程连载


Linux C编程连载——cp的实现:

  1. /**********************************************************  
  2.  * This program is use to copy src_file to dest_file  
  3.  * 1 Execute gcc -o copy copy.c  
  4.  * 2 then, copy the execute file "copy" to the /usr/bin  
  5.  * You can use command like this : copy src_file dest_file  
  6.  * Author : Tan De  
  7.  * Time   : 2011-04-04  
  8.  *********************************************************/  
  9.   
  10. #include <stdio.h>  
  11. #include <stdlib.h>  
  12. #include <unistd.h>  
  13. #include <sys/stat.h>  
  14. #include <sys/types.h>  
  15. #include <fcntl.h>  
  16.   
  17. #define BUFF_SIZE 1024  
  18.   
  19. int main(int argc, char *argv[]){  
  20.   
  21.     int src_file,dest_file;  
  22.     int real_read_len;  
  23.     unsigned char buff[BUFF_SIZE];  
  24.   
  25.     //argc is not correct  
  26.     if(argc!=3){  
  27.     printf("Error use copy!\n");  
  28.     printf("Example:\n");  
  29.     printf("copy src_file dest_file\n");  
  30.     exit(1);      
  31.     }  
  32.   
  33.     //Open src_file read only  
  34.     src_file=open(argv[1],O_RDONLY);  
  35.     //If the dest_file is not exsit, then create new one  
  36.     dest_file=open(argv[2],O_WRONLY|O_CREAT,666);  
  37.     //Open error  
  38.     if(src_file<0||dest_file<0){  
  39.     printf("Open file error\n");  
  40.     printf("Can't copy!\n");  
  41.     printf("Please check cmd : copy src_file dest_file\n");  
  42.     exit(1);  
  43.     }  
  44.   
  45.     //Copy src_file to dest_file  
  46.     while((real_read_len=read(src_file,buff,sizeof(buff)))>0){  
  47.     write(dest_file,buff,real_read_len);  
  48.     }  
  49.   
  50.     //close fd  
  51.     close(dest_file);  
  52.     close(src_file);  
  53.   
  54.     return 0;  
  55. }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 下一页
【内容导航】
第1页:cp的实现 第2页:鼠标
第3页:串口编程 第4页:基于TCP/IP的文件传输系统
第5页:关于双链表“掉链子”的问题 第6页:“混沌”贪吃蛇
第7页:变参数实现printf

相关内容