分享在linux系统下拷贝文件的两种方法:
1
使用系统调用的read和write实现文件拷贝:
1. #include <stdio.h> 2. #include <sys/types.h> 3. #include <sys/stat.h> 4. #include <fcntl.h> 5. #include <unistd.h> 6. #include <time.h> 7. #define N 32 8. 9. int main(int argc, const char *argv[]) 10. { 11. clock_t start, end; 12. double cpu_time_used; 13. start = clock(); 14. 15. int fd_r = open(argv[1], O_RDONLY); 16. if(fd_r == -1) 17. { 18. printf("open error\n"); 19. return -1; 20. } 21. 22. int fd_w = open(argv[2], O_RDWR|O_CREAT|O_TRUNC, 0664); 23. if(fd_w == -1) 24. { 25. printf("open error\n"); 26. return -1; 27. } 28. 29. char buf[N]; 30. int ret = 0; 31. 32. while((ret = read(fd_r, buf, N)) > 0) 33. { 34. write(fd_w, buf, ret); 35. } 36. printf("copy ok\n"); 37. 38. close(fd_r); 39. close(fd_w); 40. 41. end = clock(); 42. cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; 43. 44. printf("运行时间:%d s",cpu_time_used); 45. return 0; 46. }
测试:
2
使用fputc和fgetc等库函数实现文件拷贝:
1. //使用fgetc、fputc完成文件的拷贝操作 2. #include <stdio.h> 3. #include <time.h> 4. 5. int main(int argc, const char *argv[]) 6. { 7. clock_t start, end; 8. double cpu_time_used; 9. start = clock(); 10. 11. if(argc < 3) 12. { 13. printf("Usage : %s <src_file> <dst_file>\n", argv[0]); 14. return -1; 15. } 16. 17. FILE *fp_r = fopen(argv[1], "r"); 18. if(fp_r == NULL) 19. { 20. printf("fp_r fopen error\n"); 21. return -1; 22. } 23. 24. FILE *fp_w = fopen(argv[2], "w"); 25. if(fp_w == NULL) 26. { 27. printf("fp_w fopen error\n"); 28. return -1; 29. } 30. 31. int ret = 0; 32. 33. while((ret = fgetc(fp_r)) != EOF) 34. { 35. fputc(ret, fp_w); 36. } 37. printf("copy ok\n"); 38. 39. fclose(fp_r); 40. fclose(fp_w); 41. 42. end = clock(); 43. cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; 44. 45. printf("运行时间:%d s",cpu_time_used); 46. return 0; 47. }
测试:
最终目录结构: