I'm trying to write a custom sprintf to format strings, with no need to pass a variable to write output to.
What I'm doing is traversing the given string with a for loop, finding % char, moving a char forward, switch-case that next char
Here is the code:
utils.c:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utils.h>
char *concat(char *p_format, ...) {
char *p_concat_str = calloc(1, sizeof(char));
va_list args;
va_start(args, p_format);
for (unsigned int i = 0; i < strlen(p_format); ++i) {
if (p_format[i] == '%') {
i++;
void *p_arg_str = va_arg(args, char *);
/* printf("%s\n", (char *)p_arg_str); */
p_concat_str = realloc(p_concat_str, (strlen(p_arg_str) + 1));
switch (p_format[i]) {
case 's':
strcat(p_concat_str, (char *)p_arg_str);
/* printf("%s\n", (char *)p_arg_str); */
break;
}
}
p_concat_str = realloc(p_concat_str, i + 2);
p_concat_str[i] = p_format[i];
p_concat_str[i + 1] = '\0';
}
return p_concat_str;
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <utils.h>
int main() {
char *p_world = "World";
/* Hello World */
char *p_str = concat("Hello %s", p_world);
printf("Formatted str: %s | its len %lu\n", p_str, strlen(p_str));
free(p_str);
return 0;
}
But I can't realloc p_concat_str length and can't append the argument returned by va_arg to p_concat_str with strcat
This is what I got
-- Configuring done
-- Generating done
-- Build files have been written to: /home/prxvvy/workspace/cutils/cmake-build-debug
[2/2] Linking C executable cutils
Formatted str: Hello Ws | its len 8