]> gitweb.ps.run Git - onefile/commitdiff
add varargs.c
authorpatrick-scho <patrick.schoenberger@posteo.de>
Fri, 30 May 2025 20:57:47 +0000 (22:57 +0200)
committerpatrick-scho <patrick.schoenberger@posteo.de>
Fri, 30 May 2025 20:57:47 +0000 (22:57 +0200)
varargs.c [new file with mode: 0644]

diff --git a/varargs.c b/varargs.c
new file mode 100644 (file)
index 0000000..cba6ba7
--- /dev/null
+++ b/varargs.c
@@ -0,0 +1,82 @@
+void test(const char *format, ...)
+{
+    va_list argp;
+    va_start(argp, format);
+
+    int n = 0;
+    static char sep[128];
+
+    while (*format != '\0')
+    {
+        if (*format == '%')
+        {
+            format++;
+            if (*format == '%')
+            {
+                putchar('%');
+            }
+            else if (*format >= '0' && *format <= '9')
+            {
+                n = (*format) - '0';
+                format++;
+                while (*format >= '0' && *format <= '9')
+                {
+                    n *= 10;
+                    n += (*format) - '0';
+                    format++;
+                }
+                if (*format == '[')
+                {
+                    format++;
+                    int i = 0;
+                    while (*format != ']')
+                    {
+                        sep[i++] = *format;
+                        format++;
+                    }
+                    sep[i] = '\0';
+                    format++;
+                }
+                if (*format == 'd')
+                {
+                    int *ints = va_arg(argp, int *);
+                    for (int i = 0; i < n; i++)
+                    {
+                        if (i > 0)
+                            printf("%s", sep);
+                        printf("%d", ints[i]);
+                    }
+                }
+                else if (*format == 's')
+                {
+                    const char **strs = va_arg(argp, const char **);
+                    for (int i = 0; i < n; i++)
+                    {
+                        if (i > 0)
+                            printf("%s", sep);
+                        printf("%s", strs[i]);
+                    }
+                }
+            }
+            else
+            {
+                fputs("Not implemented", stdout);
+                char char_to_print = va_arg(argp, int);
+                putchar(char_to_print);
+            }
+        }
+        else
+        {
+            putchar(*format);
+        }
+        format++;
+    }
+    va_end(argp);
+}
+
+int main()
+{
+    int ints[] = {1, 2, 3, 6, 8, 2, 7, 8, 1, 245, 277254, 2642, 71, 717, 7};
+    const char *strs[2] = {"abc", "def"};
+    test("Hallo %15[ ]d %2[, ]s\n", ints, strs);
+}