C语言实现的百分比加进度条的显示程序

项目中需要设计一个远程设备升级程序,程序优化时想在数字显示升级进度的同时用类似wget的进度条的形式显示升级进度,于是写了一个简单的数字+进度条显示升级进度的程序,以下为程序的核心部分,以达到抛砖引玉的效果。


/* The progress bar like this:

     xx% [=======>             ] 

  */
  int dlbytes_size = 1 + MAX (size_grouped_len, 11);
  int progress_size = bp->width - (4 + 2 + dlbytes_size + 8 + 14);

  /* The difference between the number of bytes used,
     and the number of columns used. */
  int bytes_cols_diff = 0;

  if (progress_size < 5)
    progress_size = 0;

  /* "xx% " */
  if (bp->total_length > 0)
    {
      int percentage = 100.0 * size / bp->total_length;
      assert (percentage <= 100);

      if (percentage < 100)
        sprintf (p, "%2d%% ", percentage);
      else
        strcpy (p, "100%");
      p += 4;
    }
  else
    APPEND_LITERAL ("    ");

  /* The progress bar: "[====>      ]" or "[++==>      ]". */
  if (progress_size && bp->total_length > 0)
    {
      /* Size of the initial portion. */
      int insz = (double)bp->initial_length / bp->total_length * progress_size;

      /* Size of the downloaded portion. */
      int dlsz = (double)size / bp->total_length * progress_size;

      char *begin;
      int i;

      assert (dlsz <= progress_size);
      assert (insz <= dlsz);

      *p++ = '[';
      begin = p;

      /* Print the initial portion of the download with '+' chars, the
         rest with '=' and one '>'.  */
      for (i = 0; i < insz; i++)
        *p++ = '+';
      dlsz -= insz;
      if (dlsz > 0)
        {
          for (i = 0; i < dlsz - 1; i++)
            *p++ = '=';
          *p++ = '>';
        }

      while (p - begin < progress_size)
        *p++ = ' ';
      *p++ = ']';
    }
  else if (progress_size)
    {
      /* If we can't draw a real progress bar, then at least show
         *something* to the user.  */
      int ind = bp->tick % (progress_size * 2 - 6);
      int i, pos;

      /* Make the star move in two directions. */
      if (ind < progress_size - 2)
        pos = ind + 1;
      else
        pos = progress_size - (ind - progress_size + 5);

      *p++ = '[';
      for (i = 0; i < progress_size; i++)
        {
          if      (i == pos - 1) *p++ = '<';
          else if (i == pos    ) *p++ = '=';
          else if (i == pos + 1) *p++ = '>';
          else
            *p++ = ' ';
        }
      *p++ = ']';

      ++bp->tick;
    }



你可能感兴趣的:(C/C++编程)