-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipro_printf.c
132 lines (109 loc) · 2.99 KB
/
ipro_printf.c
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include "buf.h"
void
print_usage()
{
printf("Usage: ipro_printf [ -h ] [ -m msg ] [ -s syn ]\n"
" { format [udswW] } { args }\n");
}
int
main(int argc, char **argv)
{
const char *format, *v;
char *buf;
int opt;
size_t i, format_len;
int32_t d;
uint8_t u8; uint64_t u64;
uint32_t msg, syn, u;
struct buf h, b;
msg = 0;
syn = 0;
while ((opt = getopt(argc, argv, "hm:s:")) != -1) {
switch (opt) {
case 'h':
print_usage();
return EXIT_SUCCESS;
case 'm':
sscanf(optarg, "%"SCNu32, &msg);
break;
case 's':
sscanf(optarg, "%"SCNu32, &syn);
break;
default:
fprintf(stderr, "ipro_printf: bad format\n");
return EXIT_FAILURE;
}
}
buf_init(&b);
if (argc - optind < 1)
goto out;
if ((format_len = strlen(format = argv[optind])) != argc - optind - 1) {
fprintf(stderr, "ipro_printf: missing operand\n");
return EXIT_FAILURE;
}
/* body */
for (i = 0; i < format_len; ++i) {
v = argv[optind + 1 + i];
switch (format[i]) {
case 'u':
sscanf(v, "%"SCNu32, &u);
buf_add(&b, &u, sizeof(u));
break;
case 'd':
sscanf(v, "%"SCNd32, &d);
buf_add(&b, &d, sizeof(d));
break;
case 's':
u = aunescape(&buf, v);
buf_add(&b, &u, sizeof(u));
buf_add(&b, buf, u);
free(buf);
break;
case 'w':
sscanf(v, "%"SCNu32, &u);
buf_add_w(&b, u);
break;
case 'W':
u = (uint32_t)strlen(v);
buf_add_w(&b, u);
buf_add(&b, v, u);
break;
case 'c':
sscanf(v, "%c", &u8);
buf_add_byte(&b, u8);
break;
case 'K':
sscanf(v, "%"SCNu64, &u64);
buf_add(&b, &u64, sizeof(u64));
break;
case 'a':
u = (uint32_t)strlen(v);
buf_add(&b, v, u);
break;
default:
fprintf(stderr, "ipro_prinitf: '%c' Invalid format character\n",
format[i]);
buf_release(&b);
return EXIT_FAILURE;
}
}
out:
/* header */
buf_init(&h);
buf_add(&h, &msg, sizeof(msg));
u = (uint32_t)b.size;
buf_add(&h, &u, sizeof(u));
buf_add(&h, &syn, sizeof(syn));
write(STDOUT_FILENO, h.buf, h.size);
buf_release(&h);
if (b.size != 0)
write(STDOUT_FILENO, b.buf, b.size);
buf_release(&b);
return EXIT_SUCCESS;
}