当前位置:   article > 正文

C语言 进度条_c语言多进程下载文件并显示进度

c语言多进程下载文件并显示进度

                                                              C语言 进度条

一、简述

      记--简单的控制台下载进度条。

二、效果

       Windows:        

       Linux

三、源文件

       processBar.c文件

  1. #include <stdio.h>
  2. #include <stdlib.h> //rand(), srand()
  3. #include <time.h>
  4. #define ONEMB (1024*1024)
  5. #define ONEGB (1024*ONEMB)
  6. //将bute转化为人类容易区分的单位
  7. int convByteToHumanResult(unsigned int bytes, char* result)
  8. {
  9. int i;
  10. char uint[][5] = {"B", "Kb", "MB", "GB", "TB", "PB"};
  11. double dbBytes = bytes;
  12. if(NULL == result)
  13. {
  14. return -1;
  15. }
  16. for(i=0; dbBytes>=1024.0;i++)
  17. {
  18. dbBytes /= 1024.0;
  19. }
  20. sprintf(result, "%.2lf%s", dbBytes, uint[i]);
  21. return i;
  22. }
  23. //显示进度条
  24. void showProcessBar(unsigned int total, unsigned int recv, char* info)
  25. {
  26. int i;
  27. float frecv = recv;
  28. int percent = (int)((frecv/total) * 100);
  29. char res1[64] = {0};
  30. char sum1[64] = {0};
  31. char bar[101] = {0};
  32. for(i=0; i<percent; i++)
  33. {
  34. bar[i] = '#';
  35. }
  36. convByteToHumanResult(recv, res1);
  37. convByteToHumanResult(total, sum1);
  38. if(NULL != info)
  39. {
  40. printf("\r%s total:%s(%u Byte) recv:%s(%u Byte) [%d%%%s] ", info, sum1, total, res1, recv, percent, bar);
  41. fflush(stdout);
  42. }
  43. }
  44. int main(void)
  45. {
  46. unsigned int i;
  47. unsigned int total1 = (unsigned int)188 * ONEMB;
  48. unsigned int total2 = (unsigned int)1 * ONEGB + 267 * ONEMB;
  49. srand(time(0));//设置随机数种子
  50. printf("Start download aaa.log...\n");
  51. for(i=0;;)
  52. {
  53. showProcessBar(total1, i, "download...");
  54. if(i >= total1)
  55. {
  56. break;
  57. }
  58. i += rand()%1024;
  59. if(i>total1)
  60. {
  61. i = total1;
  62. }
  63. }
  64. printf("\nDownload aaa.log finish!\n\n");
  65. printf("Start download CProgram.zip...\n");
  66. for(i=0;;)
  67. {
  68. showProcessBar(total2, i, "download...");
  69. if(i >= total2)
  70. {
  71. break;
  72. }
  73. i += rand()%8192;
  74. if(i>total2)
  75. {
  76. i = total2;
  77. }
  78. }
  79. printf("\nDownload CProgram.zip finish!\n");
  80. return 0;
  81. }

四、总结

       4.1 回到行首使用 '\r'    printf("\r");

       4.2 擦除一个字符使用退格符'\b',然后用空格覆盖 printf("\b \b");

              注:不能擦除换行符,即只能擦除同一行的字符。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/264242
推荐阅读
相关标签
  

闽ICP备14008679号