实现Linux下带进度显示的cp命令 - xcp

来源:互联网 发布:网络春晚策划方案 编辑:程序博客网 时间:2024/05/17 07:00
Linux下复制文件的命令cp非常强大,就是有一点不是很好:没有进度提示。尤其是在复制很多大文件时,控制台仅仅停在那里什么信息都没有让人非常不爽。

当然可以通过shell脚本实现进度提示,不过我喜欢直接一点的方式:用C程序解决。

1.遍历

想要知道进度首先要统计源文件的个数和大小,然后再复制,所以需要对源文件做两次遍历。当然也可以只遍历一遍,把遍历的结果保存在内存中这样后续操作就不用再遍历了,不过我认为这样做是没有必要的。

遍历函数 walk() 接受一个函数指针参数opp_func,walk()保证对源的每一项(可能是文件也可能是目录)调用一次opp_func. 这样可以通过设置不同的opp_func用同一个遍历函数完成不同的功能。后面的代码实现了3个opp_func分别是 统计函数 sum_up, 演示函数 demo, 和真正的执行函数  action.

2.进度信息显示

进度提示要在Linux的控制台的同一行覆盖刷新,否则就不美观了.这里需要用到一个小技巧:printf 输出控制台控制字符 \r\033[K 用来把光标移动到当前行行首(不换行)并清空当前行的内容。

进度提示的刷新时机也是一个问题:单独创建一个线程用来刷新进度信息未免小题大做,如果每复制一点数据就刷新一次又过于频繁,用定时器则刚刚好。不过定时器也有定时器的问题,在附录440行提示用户是否覆盖已经存在的文件时,需要等待用户输入,此时正在运行的定时器会导致中断重启使getchar函数出错返回,需要避免这种情况。

3.安装

把附录中的源代码保存成文件xcp.c

gcc xcp.c -o xcp

sudo xcp xcp /usr/bin

xcp

3.运行结果

在我的机器上(ubuntu 12.04LTS)是这样:

运行中:

ted@ted-ThinkPad-T410:~/movies$ xcp ./BBC.野性澳洲/ ./BBC.Australia -r
1 directories 19 files 3.43GB detected.
1 directories 9 files 494.49MB copied, 14%, 22.48MB/s - 

完成:

ted@ted-ThinkPad-T410:~/movies$ xcp ./BBC.野性澳洲/ ./BBC.Australia -r
1 directories 19 files 3.43GB detected.
1 directories 19 files 3.43GB copied, 2m 30s, 23.42MB/s.

有目录个数,文件个数,字节数,用时,平均速度,复制过程中还有一个字符的小动画。嗯,差不多了。

=== 2013.11.1更新

1.支持多源文件,即可以 “xcp file1 dir1 file2 dir2... dest” 这样的方式拷贝多个文件/目录到同一个目录中。

2. 只有在递归复制目录(参数-r)时才判断是否循环复制。

=====================我是分割线=======================

PS,鄙视只贴代码不写说明的行为。

附录: xcp.c

=====================我也是=======================

[cpp] view plaincopy
  1. #define _FILE_OFFSET_BITS 64  
  2.   
  3. #include <unistd.h>  
  4. #include <stdio.h>  
  5. #include <stdlib.h>  
  6. #include <sys/stat.h>  
  7. #include <sys/types.h>  
  8. #include <dirent.h>  
  9. #include <string.h>  
  10. #include <time.h>  
  11. #include <signal.h>  
  12. #include <sys/time.h>  
  13. #include <stdarg.h>  
  14. #include <errno.h>  
  15.   
  16. /* 
  17. * 复制文件可以显示进度 
  18.  
  19. * 两个思路:遍历文件一次,把文件名记录在一个列表,后续操作直接从列表中得到文件名 
  20. * 或者遍历两遍,第一次统计,第二次执行 
  21.  
  22. * 关于进度条  
  23. * 1. 用定时器每隔1秒刷新一次要注意函数重入的问题 
  24. * 2. 两个线程工作线程统计/拷贝主线程刷新状态,似乎小题大做了 
  25. * 3. 一个线程有变化时刷新,这样就无法现实动画 
  26. * 
  27. * TODO 
  28. * 2013-10-22 
  29. * 1. 添加命令行选项的处理。 
  30. * 2. 添加文件无法访问/目录无法创建或者文件/目录已经存在的情况的处理。 
  31. * 3. 如果没有任何文件成功复制时的提示信息BUG(在有文件detected的情况下)。 
  32. * 4. 复制文件,目标是已经存在的目录名时自动添加文件名而不是直接复制。 
  33. * 5. 结束时用human_time 来显示用去的时间。 
  34.  
  35. * 2013-10-23 
  36. * 1. 统计阶段也要显示动画 
  37.  
  38. * 2013-10-24 
  39. * 1. overwrite 提示后等待用户输入和定时器冲突的问题 
  40.  
  41. * 2013-10-29 
  42. * 1. 多源拷贝在主函数做个循环,都要补齐文件名,判断是否存在等. 
  43. * 
  44. */  
  45.   
  46. #define BOOL int  
  47. #define TRUE 1  
  48. #define FALSE 0  
  49. #define MAX_FMTSTR_LENGTH 2048  /*传递给print_message函数的格式字符串最大长度*/  
  50. #define COPY_BUF_SIZE 4096 /*复制文件时每次读取的长度*/  
  51. #define MAX_PATH_LENGTH (PATH_MAX + 1)  /*路径的最大长度*/  
  52. #define GBYTES (1024 * 1024 * 1024)  
  53. #define MBYTES (1024 * 1024)  
  54. #define KBYTES 1024  
  55. #define HOUR (60 * 60)  
  56. #define MINUTE 60  
  57. #define OPP_CONTINUE 0  
  58. #define OPP_SKIP 1  
  59. #define OPP_CANCEL 2 /*walk 函数终止遍历退出*/  
  60.   
  61. #define MSGT_PROMPT 0  
  62. #define MSGT_WARNING 1  
  63. #define MSGT_ERROR 2  
  64. #define MSGT_VERBOSE 3  
  65. #define MSGT_DEMO 4  
  66.   
  67. /*启用大文件支持*/  
  68. //#define _LARGEFILE64_SOURCE  
  69. //#define _FILE_OFFSET_BITS 64  
  70.   
  71. //#ifdef _LARGEFILE64_SOURCE  
  72. //#define stat stat64  
  73. //#define fopen fopen64  
  74. //#define fread fread64  
  75. //#define fwrite fwrite64  
  76. //#endif  
  77.   
  78. typedef int (*each_opp_t)(const char*, const char*, const char*, const struct stat* st);  
  79. typedef void (*sig_handler_t)(int);  
  80.   
  81. /* 全局变量 */  
  82. int sum_file = 0;  
  83. int sum_dir = 0;  
  84. long long sum_size = 0;  
  85. int copied_file = 0;  
  86. int copied_dir = 0;  
  87. long long copied_size = 0;  
  88. time_t copy_start_time = 0;  
  89. BOOL status_pause = FALSE;  
  90. BOOL opt_d = FALSE;  
  91. BOOL opt_f = FALSE;  
  92. BOOL opt_q = FALSE;  
  93. BOOL opt_r = FALSE;  
  94. BOOL opt_v = FALSE;  
  95.   
  96. /*显示为可读数字*/  
  97. char* human_size(long long s, char *hs)  
  98. {  
  99.     if(s >= GBYTES)  
  100.     {  
  101.         sprintf(hs, "%.2fGB", (s * 1.0) / GBYTES);  
  102.     }  
  103.     else if(s >= 1024 * 1024)  
  104.     {  
  105.         sprintf(hs, "%.2fMB", (s * 1.0) / MBYTES);  
  106.     }  
  107.     else if(s > 1024)  
  108.     {  
  109.         sprintf(hs, "%.2fKB", (s * 1.0) / KBYTES);  
  110.     }  
  111.     else  
  112.     {  
  113.         sprintf(hs, "%lldB", s);  
  114.     }  
  115.   
  116.     return hs;  
  117. }  
  118.   
  119. /* human readable time */  
  120. char* human_time(time_t t, char *text)  
  121. {  
  122.     int h,m,s;  
  123.     h = (int)(t / HOUR);  
  124.     m = (int)((t % HOUR) / MINUTE);  
  125.     s = (int)(t % HOUR % MINUTE);  
  126.   
  127.     if(h > 0)  
  128.     {  
  129.         sprintf(text, "%dh %dm %ds", h, m, s);  
  130.     }  
  131.     else if(m > 0)  
  132.     {  
  133.         sprintf(text, "%dm %ds", m, s);  
  134.     }  
  135.     else  
  136.     {  
  137.         sprintf(text, "%ds", s);  
  138.     }  
  139.     return text;  
  140. }  
  141.   
  142. /* 
  143. * 先清除状态文字然后在输出信息 
  144. * 1. 状态文字总是在当前行输出不换行 
  145. * 2. printerror只能在状态文字被显示之后输出,即定时器被安装之后使用。 
  146. */  
  147. void print_message(int t, const char* fmt, ...)  
  148. {  
  149.     char real_fmt[MAX_FMTSTR_LENGTH];  
  150.     va_list args;  
  151.     va_start(args, fmt);  
  152.   
  153.     if(opt_q && (t == MSGT_WARNING || t == MSGT_ERROR))  
  154.     {  
  155.         /*quiet, don't output warning nor error message*/  
  156.     }  
  157.     else  
  158.     {  
  159.         sprintf(real_fmt, "\r\033[K%s", fmt);  
  160.         vprintf(real_fmt, args);  
  161.     }  
  162. }  
  163.   
  164. /*连接目录字符串,主要处理末尾/的问题,frt snd 两个参数不能同时为空那样没有意义*/  
  165. char* make_path(char *dest, const char *frt, const char *snd)  
  166. {  
  167.     if(NULL == frt || strlen(frt) == 0)  
  168.     {  
  169.         sprintf(dest, "%s", snd);  
  170.     }  
  171.     else if(NULL == snd || strlen(snd) == 0)  
  172.     {  
  173.         sprintf(dest, "%s", frt);  
  174.     }  
  175.     else  
  176.     {  
  177.         if(frt[strlen(frt) - 1] == '/')  
  178.         {  
  179.             sprintf(dest, "%s%s", frt, snd);  
  180.         }  
  181.         else  
  182.         {  
  183.             sprintf(dest, "%s/%s", frt, snd);  
  184.         }  
  185.     }  
  186.     return dest;  
  187. }  
  188.   
  189. /*显示进度条*/  
  190. void show_status(BOOL finish)  
  191. {  
  192.     int percent,i;  
  193.     char animate[4];  
  194.     static int animate_pos = -1;  
  195.     time_t cur_time;  
  196.     char speed[512];  
  197.     char hs[512];  
  198.     long long sp = 0;  
  199.     char ht[512];  
  200.   
  201.     animate[0] = '-';  
  202.     animate[1] = '/';  
  203.     animate[2] = '|';  
  204.     animate[3] = '\\';  
  205.   
  206.     time(&cur_time);  
  207.     if(sum_size == 0)  
  208.     {  
  209.         percent = 0;  
  210.     }  
  211.     else  
  212.     {  
  213.         percent = (copied_size * 1.0 / sum_size) * 100;  
  214.     }  
  215.   
  216.     if(cur_time > copy_start_time)  
  217.     {  
  218.         sp = copied_size / (cur_time - copy_start_time);  
  219.         sprintf(speed, "%s/s", human_size(sp, hs));  
  220.     }  
  221.     else  
  222.     {  
  223.         sprintf(speed, "-");  
  224.     }  
  225.   
  226.     human_size(copied_size, hs);  
  227.     if(finish)  
  228.     {  
  229.         printf("\r\033[K%d directories %d files %s copied, %s, %s.\n",\  
  230.             copied_dir, copied_file, hs, human_time(cur_time - copy_start_time, ht), speed);  
  231.     }  
  232.     else  
  233.     {  
  234.         printf("\r\033[K%d directories %d files %s copied, %d%%, %s %c ", \  
  235.             copied_dir, copied_file, hs, percent, speed, animate[animate_pos = (animate_pos + 1) % 4]);  
  236.     }  
  237.     fflush(stdout);  
  238. }  
  239.   
  240. /*定时器处理函数*/  
  241. void timer_handler(int signum)  
  242. {  
  243.     if(!status_pause)  
  244.     {  
  245.         show_status(FALSE);  
  246.     }     
  247. }  
  248.   
  249. /*安装/删除定时器*/  
  250. void install_timer(size_t sec, sig_handler_t  handler_func)  
  251. {  
  252.     struct sigaction act;  
  253.     struct itimerval tick;  
  254.   
  255.     if(sec > 0)  
  256.     {  
  257.         act.sa_handler = handler_func;  
  258.     }  
  259.     else  
  260.     {  
  261.         act.sa_handler = SIG_DFL;  
  262.     }  
  263.     sigemptyset(&act.sa_mask);  
  264.     act.sa_flags = 0;  
  265.     sigaction(SIGALRM, &act, 0);  
  266.       
  267.     memset(&tick, 0, sizeof(tick));  
  268.     tick.it_value.tv_sec = sec;  
  269.     tick.it_value.tv_usec = 0;  
  270.     tick.it_interval.tv_sec = sec;  
  271.     tick.it_interval.tv_usec = 0;  
  272.   
  273.     setitimer(ITIMER_REAL, &tick, 0);  
  274. }  
  275.   
  276. /*  
  277. * 遍历函数 
  278. * 遍历函数只保证源文件/文件夹的每一项都调用一次opp函数 
  279. * 由opp函数的返回值决定是否继续扫描 
  280. * 采用“串烧”式程序风格 
  281. * 只有一种情况下返回值为FALSE:opp 函数返回OPP_CANCEL 
  282. */  
  283. int walk(const char* path_from, const char* path_to, const char* path_tree, each_opp_t opp)  
  284. {  
  285.     struct stat st;  
  286.     DIR* dir = NULL;  
  287.     struct dirent *entry = NULL;  
  288.     char path_tree_new[MAX_PATH_LENGTH];  
  289.     char path_from_full[MAX_PATH_LENGTH];  
  290.     int ret_val = OPP_CONTINUE;  
  291.   
  292.     /*获得源的属性*/  
  293.     make_path(path_from_full, path_from, path_tree);  
  294.     if(-1 == stat(path_from_full, &st))  
  295.     {  
  296.         print_message(MSGT_ERROR, "can't access \"%s\".\n", path_from_full);  
  297.         return OPP_SKIP;  
  298.     }  
  299.   
  300.     /*调用一次处理函数,处理当前项*/  
  301.     if((ret_val = opp(path_from, path_to, path_tree, &st)) != OPP_CONTINUE)  
  302.     {  
  303.         return ret_val;  
  304.     }  
  305.               
  306.     /*如果是目录,则浏览目录,否则结束*/  
  307.     if(!S_ISDIR(st.st_mode))  
  308.     {  
  309.         return OPP_CONTINUE;  
  310.     }  
  311.   
  312.     /*打开目录*/  
  313.     if(!(dir = opendir(path_from_full)))  
  314.     {  
  315.         print_message(MSGT_ERROR, "can't open directory \"%s\".\n", path_from_full);  
  316.         return OPP_SKIP;  
  317.     }  
  318.   
  319.     /*浏览目录*/  
  320.     while((entry = readdir(dir)) != NULL)  
  321.     {  
  322.         /*构建path_tree_new*/  
  323.         make_path(path_tree_new, path_tree, entry->d_name);  
  324.         make_path(path_from_full, path_from, path_tree_new);  
  325.       
  326.         /*无法访问 skip*/  
  327.         if(-1 == stat(path_from_full, &st))  
  328.         {  
  329.             print_message(MSGT_ERROR, "skip, can't access \"\".\n", path_from_full);  
  330.             continue;  
  331.         }  
  332.   
  333.         /* 忽略 . 和 .. */  
  334.         if(S_ISDIR(st.st_mode) && (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0))  
  335.         {  
  336.             continue;  
  337.         }  
  338.   
  339.         if(S_ISDIR(st.st_mode) && opt_r)  
  340.         {  
  341.           /*递归处理子目录*/  
  342.             if(walk(path_from, path_to, path_tree_new, opp) == OPP_CANCEL)  
  343.             {  
  344.                 ret_val = OPP_CANCEL;  
  345.                 break;  
  346.             }  
  347.         }  
  348.         else  
  349.         {  
  350.             /*处理函数处理一个子项*/  
  351.             if(opp(path_from, path_to, path_tree_new, &st) == OPP_CANCEL)  
  352.             {  
  353.                 ret_val = OPP_CANCEL;  
  354.                 break;  
  355.             }  
  356.         }  
  357.     }  
  358.     closedir(dir);  
  359.     return ret_val;  
  360. }  
  361.   
  362. /* 统计函数 */  
  363. int sum_up(const char* path_from, const char* path_to, const char* path_tree, const struct stat* st)  
  364. {  
  365.     if(S_ISREG(st->st_mode))  
  366.     {  
  367.         sum_file++;  
  368.         sum_size += st->st_size;  
  369.     }  
  370.     else if(S_ISDIR(st->st_mode))  
  371.     {  
  372.         sum_dir++;  
  373.     }  
  374.     else  
  375.     {  
  376.         print_message(MSGT_WARNING, "skip:%s\n", path_tree);  
  377.     }  
  378.     return OPP_CONTINUE;  
  379. }  
  380.   
  381. /*demo*/  
  382. int demo(const char* path_from, const char* path_to, const char* path_tree, const struct stat* st)  
  383. {  
  384.     char path_from_full[MAX_PATH_LENGTH];  
  385.     char path_to_full[MAX_PATH_LENGTH];  
  386.       
  387.     make_path(path_from_full, path_from, path_tree);  
  388.     make_path(path_to_full, path_to, path_tree);  
  389.   
  390.     if(S_ISREG(st->st_mode))  
  391.     {  
  392.         print_message(MSGT_DEMO, "cp \"%s\" -> \"%s\".\n", path_from_full, path_to_full);  
  393.     }  
  394.     else if(S_ISDIR(st->st_mode))  
  395.     {  
  396.         print_message(MSGT_DEMO, "mkdir \"%s\".\n", path_to_full);  
  397.     }  
  398.     else  
  399.     {  
  400.         print_message(MSGT_WARNING, "skip \"%s\"\n", path_tree);  
  401.     }  
  402.     return OPP_CONTINUE;  
  403.   
  404. }  
  405.   
  406. /* 操作 */  
  407. int action(const char* path_from, const char* path_to, const char* path_tree, const struct stat* st)  
  408. {  
  409.     int ret_val = OPP_CONTINUE;  
  410.     char path_from_full[MAX_PATH_LENGTH];  
  411.     char path_to_full[MAX_PATH_LENGTH];  
  412.     size_t rd, wr, swr;  
  413.     char buf[COPY_BUF_SIZE];  
  414.     FILE *src_file, *dest_file;   
  415.     BOOL over_write = FALSE;  
  416.     int cmd;  
  417.     BOOL skip = FALSE;  
  418.     struct stat st_dest;  
  419.       
  420.     make_path(path_from_full, path_from, path_tree);  
  421.     make_path(path_to_full, path_to, path_tree);  
  422.   
  423.     if(S_ISREG(st->st_mode))  
  424.     {  
  425.         /* regular file */  
  426.         if(opt_v)  
  427.         {  
  428.             print_message(MSGT_VERBOSE, "cp \"%s\" -> \"%s\".\n", path_from_full, path_to_full);  
  429.         }  
  430.   
  431.         if(strcmp(path_from_full, path_to_full) == 0)  
  432.         {  
  433.             ret_val = OPP_SKIP;  
  434.             print_message(MSGT_ERROR, "skip, \"%s\" and \"%s\" are the same.\n", path_from_full, path_to_full);  
  435.         }  
  436.         else if(src_file = fopen(path_from_full, "rb"))  
  437.         {  
  438.             do  
  439.             {  
  440.                 /*询问是否可以覆盖*/  
  441.                 if(!opt_f && 0 == access(path_to_full, F_OK))   
  442.                 {  
  443.                     /* 应该先停止计时器,否则在等待用户输入时如果有定时器被触发,会导致 getchar()停止等待并返回 EOF*/  
  444.                     status_pause = TRUE;  
  445.                     print_message(MSGT_PROMPT, "overwrite \"%s\"? ([y] yes,[n] no, [a] all, [c] cancel)", path_to_full);  
  446.                     while(1)  
  447.                     {  
  448.                         cmd = getchar();  
  449.   
  450.                         /*中断重启 由于有一个定时器正在运行,在等待用户输入的过程中getchar会被中断返回*/  
  451.                         if(-1 == cmd) continue;  
  452.   
  453.                         /*skip useless chars of inputed line*/  
  454.                         if(cmd != '\n')  
  455.                         {  
  456.                             while(getchar() != '\n');  
  457.                         }  
  458.   
  459.                         if('y' == cmd)  
  460.                         {  
  461.                             break;  
  462.                         }  
  463.                         else if('n' == cmd)  
  464.                         {  
  465.                             skip = TRUE;  
  466.                             ret_val = OPP_SKIP;  
  467.                             break;  
  468.                         }  
  469.                         else if('a' == cmd)  
  470.                         {  
  471.                             opt_f = TRUE;  
  472.                             break;  
  473.                         }  
  474.                         else if('c' == cmd)  
  475.                         {  
  476.                             /* skip current file and cancel walk progress */  
  477.                             skip = TRUE;  
  478.                             ret_val = OPP_CANCEL;  
  479.                             break;  
  480.                         }  
  481.                         else  
  482.                         {  
  483.                             /* unknown command */  
  484.                         }  
  485.                     }  
  486.                     status_pause = FALSE;  
  487.                   
  488.                     /* ship current file */  
  489.                     if(skip) break;  
  490.                 }  
  491.                   
  492.                 /* open target file for write */  
  493.                 if(dest_file = fopen(path_to_full, "wb"))  
  494.                 {  
  495.                     while((rd = fread(buf, 1, COPY_BUF_SIZE, src_file)) > 0)  
  496.                     {  
  497.                         wr = 0;  
  498.                         do  
  499.                         {  
  500.                             swr = fwrite(buf + wr, 1, rd - wr, dest_file);  
  501.                             wr += swr;  
  502.                         }  
  503.                         while(swr > 0 && wr < rd);  
  504.                         copied_size += rd;  
  505.                       
  506.                         if(wr != rd)  
  507.                         {  
  508.                             /*只有部分文件被复制也视为成功因为文件系统中已经有这个文件的记录了*/  
  509.                             print_message(MSGT_ERROR, "write file error %s.\n", path_to_full);  
  510.                             break;  
  511.                         }  
  512.                     }  
  513.                     fclose(dest_file);  
  514.                     chmod(path_to_full, st->st_mode);  
  515.                     copied_file++;  
  516.                 }  
  517.                 else  
  518.                 {  
  519.                     ret_val = OPP_SKIP;  
  520.                     print_message(MSGT_ERROR, "skip, can't open target file \"%s\"\n", path_to_full);  
  521.                 }  
  522.             }while(0);  
  523.   
  524.             fclose(src_file);  
  525.         }  
  526.         else  
  527.         {  
  528.             ret_val = OPP_SKIP;  
  529.             print_message(MSGT_ERROR, "skip, can't open source file \"%s\"\n", path_from_full);  
  530.         }  
  531.     }  
  532.     else if(S_ISDIR(st->st_mode))  
  533.     {  
  534.         /* directories */  
  535.         if(opt_v)  
  536.         {  
  537.             print_message(MSGT_VERBOSE, "mkdir \"%s\"\n", path_to_full);  
  538.         }  
  539.   
  540.         if(0 == stat(path_to_full, &st_dest))  
  541.         {  
  542.             /*path_to_full already exist*/  
  543.             if(S_ISDIR(st_dest.st_mode))  
  544.             {  
  545.                 copied_dir++;  
  546.             }  
  547.             else  
  548.             {  
  549.                 ret_val = OPP_SKIP;  
  550.                 print_message(MSGT_WARNING, "skip, \"%s\" exists and it's not a directory.\n", path_to_full);  
  551.             }  
  552.         }  
  553.         else  
  554.         {  
  555.             /*try to make a new directory*/  
  556.             if(0 == mkdir(path_to_full, st->st_mode))  
  557.             {  
  558.                 chmod(path_to_full, st->st_mode);  
  559.                 copied_dir++;  
  560.             }  
  561.             else  
  562.             {  
  563.                 ret_val = OPP_SKIP;  
  564.                 print_message(MSGT_ERROR, "skip, \"%s\" mkdir failed.\n", path_to_full);  
  565.             }  
  566.         }  
  567.     }  
  568.     else  
  569.     {  
  570.         ret_val = OPP_SKIP;  
  571.         print_message(MSGT_WARNING, "skip, \"%s\" is not a file nor directory.\n", path_to_full);  
  572.     }  
  573.   
  574.     return ret_val;  
  575. }  
  576.   
  577. /*使用说明*/  
  578. void usage()  
  579. {  
  580.     printf("xcp - by Q++ Studio 2013-11-1\n");  
  581.     printf("description:cp with progress\n");  
  582.     printf("synopsis: xcp [OPTIONS] src1 [src2 ... srcn] dest\n\n");  
  583.     printf("[OPTIONS]\n");  
  584.     printf("-r:recusive copy sub directories.\n");  
  585.     printf("-f:force overwrite without prompt.\n");  
  586.     printf("-q:quiet no warning/error message.\n");  
  587.     printf("-d:demo,do not copy,output message only.\n");  
  588.     printf("-v:verbos output.\n");  
  589.     printf("-h:show usage message.\n");  
  590. }  
  591.   
  592. /*禁止循环复制,即目标文件/文件夹不能包含在源文件/文件夹中*/  
  593. BOOL is_self_copy(const char* src, const char* dest)  
  594. {  
  595.     /*严格的做法应该先把src和dest都转化为绝对路径然后在比较,不过 
  596.      *Linux下的相对路径比较麻烦有 ~ ./ ../ ../../ 等... 
  597.     */  
  598.     char c;  
  599.     char* sub = strstr(dest, src);  
  600.   
  601.     if(sub)  
  602.     {  
  603.         c = sub[strlen(src)];  
  604.         return c == '\0' || c == '/' || src[strlen(src) - 1] == '/';  
  605.     }  
  606.     else  
  607.     {  
  608.         return FALSE;  
  609.     }  
  610. }  
  611.   
  612. /*主函数,做两次遍历*/  
  613. int main(int argc, char* args[])  
  614. {  
  615.     int i = 0;  
  616.     char *path_from = NULL, *path_to = NULL, *file_name = NULL;  
  617.     char path_to_fixed[MAX_PATH_LENGTH];  
  618.     struct stat st_src, st_dest;  
  619.     char human_readable_size[200];  
  620.     int opt;  
  621.     BOOL help = FALSE;  
  622.       
  623.     while((opt = getopt(argc, args, "rfqdhv")) != -1)  
  624.     {  
  625.         switch(opt)  
  626.         {  
  627.             case 'r':  
  628.                 opt_r = TRUE;  
  629.                 break;  
  630.             case 'f':  
  631.                 opt_f = TRUE;  
  632.                 break;  
  633.             case 'q':  
  634.                 opt_q = TRUE;  
  635.                 break;  
  636.             case 'd':  
  637.                 opt_d = TRUE;  
  638.                 break;  
  639.             case 'h':  
  640.                 help = TRUE;  
  641.                 break;  
  642.             case 'v':  
  643.                 opt_v = TRUE;  
  644.                 break;  
  645.             case '?':  
  646.                 printf("unknown option: %c\n", optopt);  
  647.                 help = TRUE;  
  648.                 break;  
  649.             default:  
  650.                 break;  
  651.         }  
  652.     }  
  653.       
  654.     if(help || optind + 2 > argc)  
  655.     {  
  656.         usage();  
  657.         return 1;  
  658.     }  
  659.   
  660.     /* 第一次遍历:统计 */  
  661.     sum_file = 0;  
  662.     sum_dir = 0;  
  663.     sum_size = 0;  
  664.   
  665.     path_to = args[argc - 1];  
  666.     for(i = optind; i < argc -1; ++i)  
  667.     {  
  668.         path_from = args[i];  
  669.         walk(path_from, path_to, NULL, sum_up);  
  670.     }  
  671.   
  672.     if(sum_file == 0 && sum_dir == 0)  
  673.     {  
  674.         printf("nothing found.\n");  
  675.     }  
  676.     else  
  677.     {  
  678.         human_size(sum_size, human_readable_size);  
  679.         printf("%d directories %d files %s detected.\n", sum_dir, sum_file, human_readable_size);  
  680.           
  681.         /* 第二次遍历:执行*/  
  682.         copied_file = 0;  
  683.         copied_dir = 0;  
  684.         copied_size = 0;  
  685.   
  686.         // 设置一个定时器,每隔1秒显示一下进度   
  687.         time(©_start_time);  
  688.         show_status(FALSE);  
  689.         install_timer(1, timer_handler);  
  690.   
  691.         for(i = optind; i < argc - 1; ++i)  
  692.         {  
  693.             path_from = args[i];  
  694.             path_to = args[argc - 1];  
  695.   
  696.             /*源是否存在*/  
  697.             if(-1 == stat(path_from, &st_src))  
  698.             {  
  699.                     print_message(MSGT_ERROR, "\"%s\" doesn't exist.\n", path_from);  
  700.                     continue;  
  701.             }  
  702.           
  703.             /* 
  704.             * 如果源是文件而且目标是已经存在的目录,则自动补齐文件名 
  705.             * 如果目标是已经存在的文件,先判断是否指向同一个文件 inode number 
  706.             */  
  707.             if(S_ISREG(st_src.st_mode))  
  708.             {  
  709.                 if((0 == stat(path_to, &st_dest)) && S_ISDIR(st_dest.st_mode))  
  710.                 {  
  711.                     file_name = strrchr(path_from, '/');  
  712.                     path_to = make_path(path_to_fixed, path_to, file_name ? file_name + 1 : path_from);  
  713.                 }  
  714.             }  
  715.             else if(S_ISDIR(st_src.st_mode))  
  716.             {  
  717.                 if(opt_r && is_self_copy(path_from, path_to))  
  718.                 {  
  719.                     /*源是目录时要防止循环复制*/  
  720.                     print_message(MSGT_ERROR, "can't xcp \"%s\" -> \"%s\"\n", path_from, path_to);  
  721.                     continue;  
  722.                 }  
  723.             }  
  724.             else  
  725.             {  
  726.                 print_message(MSGT_WARNING, "skip \"%s\" not a file nor a directory.\n", path_from);  
  727.                 continue;  
  728.             }  
  729.   
  730.             if(opt_d)  
  731.             {  
  732.                 walk(path_from, path_to, NULL, demo);   
  733.             }  
  734.             else  
  735.             {  
  736.                 walk(path_from, path_to, NULL, action);  
  737.             }  
  738.         }  
  739.         install_timer(0, NULL);  
  740.         show_status(TRUE);  
  741.     }  
  742.   
  743.     return 0;  
  744. }  
0 0
原创粉丝点击