歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux C編程連載

Linux C編程連載

日期:2017/3/1 11:18:00   编辑:Linux編程

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. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <unistd.h>
  12. #include <sys/stat.h>
  13. #include <sys/types.h>
  14. #include <fcntl.h>
  15. #define BUFF_SIZE 1024
  16. int main(int argc, char *argv[]){
  17. int src_file,dest_file;
  18. int real_read_len;
  19. unsigned char buff[BUFF_SIZE];
  20. //argc is not correct
  21. if(argc!=3){
  22. printf("Error use copy!\n");
  23. printf("Example:\n");
  24. printf("copy src_file dest_file\n");
  25. exit(1);
  26. }
  27. //Open src_file read only
  28. src_file=open(argv[1],O_RDONLY);
  29. //If the dest_file is not exsit, then create new one
  30. dest_file=open(argv[2],O_WRONLY|O_CREAT,666);
  31. //Open error
  32. if(src_file<0||dest_file<0){
  33. printf("Open file error\n");
  34. printf("Can't copy!\n");
  35. printf("Please check cmd : copy src_file dest_file\n");
  36. exit(1);
  37. }
  38. //Copy src_file to dest_file
  39. while((real_read_len=read(src_file,buff,sizeof(buff)))>0){
  40. write(dest_file,buff,real_read_len);
  41. }
  42. //close fd
  43. close(dest_file);
  44. close(src_file);
  45. return 0;
  46. }
Copyright © Linux教程網 All Rights Reserved