~laumann/C

ref: 74c6c80ca891acc54bb96e3aac560ca2ce1635e4 C/progress/use_progress.c -rw-r--r-- 2.1 KiB
74c6c80c — Thomas Bracht Laumann Jespersen Added help message and -h,--help option. 9 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "progress.h"
#include <unistd.h>
#include <string.h>

#define TOTAL	300
#define DELAY	200

static char usage_string[] =
	"Usage: use_progress [options]...\n\n"
	"Options:\n"
	"  -t, --total <int>     The total progress.\n"
	"  -d, --delay <int>     The delay to add.\n"
	"  -m, --message <msg>   Set process message.\n"
	"  -h, --help            Print this help message and exit.\n";

/* Keep the configuration in a struct */
static struct {
	int delay;
	int total;
	char *msg;
} config = {
	/* Defaults */
	.delay = DELAY, 
	.total = TOTAL,
	.msg   = "Process"
};

int
parse_int_arg(const char *opt, const char *arg, int *target)
{
	int ok = sscanf(arg, "%d", target);
	if (!ok) {
		printf("Wrong format of argument to %s: %s\n", opt, arg);
		exit(EXIT_FAILURE);
	}
	return ok;
}

void
read_cmd_args(int nargs, char **argv)
{
	const char *arg;
	int i;


	for (i=0 ; i < nargs ; i++) {
		arg = argv[i];
		if (!strcmp(arg, "-d") || !strcmp(arg, "--delay")) {
			if (i+1 > nargs) {
				printf("Missing integer argument to %s.\n", arg);
				exit(EXIT_FAILURE);
			}
			parse_int_arg(arg, argv[++i], &config.delay);
		} else if (!strcmp(arg, "-t") || !strcmp(arg, "--total")) {
			if (i+1 > nargs) {
				printf("Missing integer argument to %s.\n", arg);
				exit(EXIT_FAILURE);
			}
			parse_int_arg(arg, argv[++i], &config.total);
		} else if (!strcmp(arg, "-m") || !strcmp(arg, "--message")) {
			if (i+1 > nargs) {
				printf("Missing string argument to %s.\n", arg);
				exit(EXIT_FAILURE);
			}
			config.msg = argv[++i]; /* No errors here */
		} else if (!strcmp(arg, "-h") || !strcmp(arg, "--help")) {
			printf("%s", usage_string);
			exit(EXIT_SUCCESS);
		} else {
			if (arg[0] == '-')
				printf("Unrecognized option: %s\n", arg);
			else
				printf("Unrecognized argument: %s\n", arg);
		}
	}
}

int
main(int argc, char** argv)
{
	/* Command-line arguments */
	if (argc > 1)
		read_cmd_args(--argc, ++argv);

	struct progress *p = start_progress(config.msg, config.total);
	int i = 0;

	while (i < config.total) {
		usleep(i*config.delay);
		display_progress(p, ++i);
	}
	
	stop_progress_msg(&p, "Done");

	exit(EXIT_SUCCESS);
}