通常, 控制台程序在执行一个漫长的任务时,需要实时显示当前进度信息, 本文演示了类似GUI进度条控件的实现.
由于需要实时更新进度条信息,并且是要在同一行显示,所以需要用到回车转义字符'\r'.
首先是进度条结构体的定义:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#define bool unsigned char
#define true 1
#define false 0
struct progress_bar_info {
const char *name;
bool interactive;
long init_length;
long step; //步长
long total_length;
int width;
char *buffer;
};
接着是几个帮助函数, 主要是获取控制台屏幕大小:
static int
get_screen_width(void)
{
int screen_width = getenv("COLUMNS");
return screen_width;
}
static int
get_screen_height(void)
{
int screen_height = getenv("LINES");
return