Re: Graphical Bar Code?

From: Mike Stilson (
Date: 07/25/02

On Thu, Jul 25, 2002 at 02:24:38AM -0700, Mathew Earle Reuther wrote:
>Does anyone have any code they'd be willing to share which draws some kind
>of graphical representation of a percentage?  I'm thinking of doing this
>kind of a bar to track progression or status of certain fields.  If anyone
>else has some code they'd be willing to toss my way so I can work with it,
>I'd be apprecative. :)

(It's amazing the number of li'l routines you add to your libraries over
some years then forget about)

Here's two ways in a li'l demo program.  One uses a separate function to
build a string, which has the advantage of being able to handle any
sized string of bar chars.  Just remember to free the string up when
Method 2 just uses a li'l trick with printf and an arbitrarily long
string of chars to use as a bar.  (It works with send_to_char, in case
you were worried)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define BAR_CHAR '*'

char *percent_bar(int, int, int);

char *percent_bar(int val, int max, int scale)
        char *bar = NULL;
        int percent = 0;
        int num_chars;

        if(!max || !scale)

        percent = (val * 100) / max;
        num_chars = percent / scale;

        bar = (char *)malloc(num_chars+1);
        memset(bar, BAR_CHAR, num_chars);
        bar[num_chars] = '\0';

int main(int ac, char *av[])
        int num, max, scale;
        int bar_len;
        char *p_bar = NULL;
        /* Enough for 120% at scale:1 */
        const char bar[] = "************************************************************************************************************************";

        if(ac < 4) exit(1);

        num = atoi(*(++av));
        max = atoi(*(++av));
        scale = atoi(*(++av));

        if(max && scale)
                bar_len = ((num * 100) / max) / scale;
                bar_len = 0;

        p_bar = percent_bar(num, max, scale);

        fprintf(stdout, "Percent: %s\n", p_bar);
        fprintf(stdout, "Bar: %.*s\n", bar_len, bar);

        if(p_bar) free(p_bar);


$ ./percent 12 72 1
Percent: ****************
Bar: ****************

Windows has detected that you have moved your mouse.
Your system must now be restarted for the changes to take effect.
        - Unknown

   | FAQ: |
   | Archives: |
   | Newbie List:   |

This archive was generated by hypermail 2b30 : 06/25/03 PDT