-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5-buffer_1024.c
executable file
·58 lines (45 loc) · 1.98 KB
/
5-buffer_1024.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>
#include <unistd.h> // For write system call
#define BUFFER_SIZE 1024
// Custom implementation of printf with support for 'u', 'o', 'x', 'X' conversion specifiers.
// 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, ...);
// Helper function to print an unsigned integer in binary format
void print_binary(unsigned int num);
int _printf(const char *format, ...) {
va_list args;
va_start(args, format);
int count = 0; // To keep track of the number of characters printed
// Buffer to store the output before calling write
char buffer[BUFFER_SIZE];
int buffer_index = 0;
// 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) {
// (Previous cases remain the same)
// if you wish to use the previous case take a referrence from file 4
default:
// Invalid specifier, ignore it.
break;
}
} else {
// If the character is not '%', store it in the buffer.
buffer[buffer_index++] = *format;
count++;
}
// If the buffer is full or we reach the end of the format string, write the buffer to stdout.
if (buffer_index >= BUFFER_SIZE || *(format + 1) == '\0') {
write(1, buffer, buffer_index);
buffer_index = 0; // Reset buffer index for the next iteration
}
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.
}
// (print_binary and other helper functions remain the same)