ui.c
/**
* Project 1 "UI" example
*/
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
void percentage_bar(float value, char buf[30])
{
if (value < 0.0) value = 0.0;
if (value > 1.0) value = 1.0;
char bar[] = "--------------------";
int hashes = (int) (value * strlen(bar));
for (int i = 0; i < hashes; i++) {
bar[i] = '#';
}
snprintf(buf, 30, "[%s] %.1f%%", bar, value * 100);
}
int main(void)
{
unsigned int counter = 0;
while (true)
{
// Option 1 to create our "UI": clear the screen each iteration, and
// redraw the whole thing. We can clear the string with this xterm
// control sequence:
//printf("\033[2J");
char bar_buf[30] = { 0 };
percentage_bar(rand() / (float) RAND_MAX, bar_buf);
puts("");
printf("Hostname: %s\n", "???");
printf(" Kernel: %s\n", "???");
printf(" CPUs: %s\n", "???");
printf(" Memory: %s\n", "???");
puts("");
// If we expect a number to be a certain size, we can add padding after
// it to ensure any old values are overwritten (mainly if the number
// gets smaller... won't happen in this example):
printf(" Counter: %-*d\n", 10, counter++);
// Add extra space after the bar to clean up the previously-printed
// value (in case the new value is a smaller string than the previous)
printf(" Bar: %s \n", bar_buf);
puts("");
// Wait 1 second to redraw.
sleep(1);
// Option 2, which can look a bit nicer. Instead of clearing the whole
// screen, simply move back up and overwrite the old values in place:
printf("\033[%dA", 9); // move the cursor up 9 lines
}
return 0;
}