-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_printf_v1.c
More file actions
95 lines (81 loc) · 2.04 KB
/
simple_printf_v1.c
File metadata and controls
95 lines (81 loc) · 2.04 KB
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
#include <stdarg.h>
#include <stdio.h>
/*
* Copyright 2023, J. Zbiciak <joe.zbiciak@leftturnonly.info>
* Author: Joe Zbiciak <joe.zbiciak@leftturnonly.info>
* SPDX-License-Identifier: CC-BY-SA-4.0
*/
/* Prints a signed integer to stdout. */
void print_int(int d) {
unsigned u = d;
/*
* Handle negative numbers. This might look odd, but it avoids undefined
* behavior for the largest negative number by negating the _unsigned_ value
* after testing the sign of the signed value.
*/
if (d < 0) {
putchar('-');
u = -u;
}
/* Inefficient, but portable. */
unsigned pow10 = 1;
unsigned tmp = u;
while (tmp >= 10) {
pow10 *= 10;
tmp /= 10;
}
/* Now print the decimalized value. */
while (pow10 > 0) {
putchar('0' + u / pow10);
u %= pow10;
pow10 /= 10;
}
}
/* Simplified printf that only understands %s, %d, and %%. */
void simple_printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
for (int ch = *fmt++; ch; ch = *fmt++) {
/* If it's not %, just print the character. */
if (ch != '%') {
fputc(ch, stdout);
continue;
}
/* It's (potentially) a conversion. Let's take a look. */
int conv = *fmt++;
switch (conv) {
case 's': {
/* %s is a string. */
const char *s = va_arg(args, const char *);
fputs(s, stdout);
break;
}
case 'd': {
/* %d is a signed integer. */
int d = va_arg(args, int);
print_int(d);
break;
}
case '%': {
/* %% prints '%' */
putchar('%');
break;
}
default: {
/* Not a valid conversion. Print the '%' and back up. */
putchar('%');
--fmt;
break;
}
}
}
va_end(args);
}
int main() {
simple_printf("Hello %s, the answer is %d.\n", "world", 42);
simple_printf("Zero: %d\n", 0);
simple_printf("Positive: %d\n", 123456789);
simple_printf("Negative: %d\n", -123456789);
simple_printf("Print a percent: %%\n");
simple_printf("Invalid conversion: %q\n");
}