-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1-_printf.c
executable file
·58 lines (52 loc) · 2 KB
/
1-_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
#include <stdio.h>
#include <stdarg.h>
// Custom implementation of printf with basic support for conversion specifiers 'c', 's', and '%'.
// Returns the number of characters printed (excluding the null byte used to end output to strings).
// Writes output to stdout, the standard output stream.
int _printf(const char *format, ...) {
va_list args;
va_start(args, format);
int count = 0; // To keep track of the number of characters printed
// Loop through the format string until we reach the end (null terminator).
while (*format) {
if (*format == '%') {
format++; // Move past the '%'
char specifier = *format; // Get the conversion specifier
switch (specifier) {
case 'c': {
// For 'c', get the next argument of type int and print it as a character.
char c = va_arg(args, int);
putchar(c);
count++;
break;
}
case 's': {
// For 's', get the next argument of type char* (string) and print it.
char *str = va_arg(args, char *);
while (*str) {
putchar(*str);
str++;
count++;
}
break;
}
case '%': {
// For '%', print a single percent sign.
putchar('%');
count++;
break;
}
default:
// Invalid specifier, ignore it.
break;
}
} else {
// If the character is not '%', simply print it.
putchar(*format);
count++;
}
format++; // Move to the next character in the format string
}
va_end(args); // Clean up the variable argument list.
return count; // Return the total number of characters printed.
}