I'm trying to do a naive implementation of the C-standard function printf. So far I've just written some testing code to help me better understand the use of variable arguments lists. However, I don't know why my output contains an extra line.
Here is my code:
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
void print_test_helper(char *string, va_list args)
{
while (*string)
{
if (*string == '%')
{
string = string + 2; //increment pointer by two spots to "\n"
printf("%s", (va_arg(args, char*)));
}
else
{
write(1, &*string, 1);
string++;
}
}
}
void print_test(char *string, ...)
{
va_list ap;
va_start(ap, string);
print_test_helper(string, ap);
}
int main()
{
print_test("this is a %s\n", "string");
return 0;
}
The way I see it, my print_test_helper should keep writing the string passed to it up until it sees the '%' character, after which it skips two spots to the newline character. The function then calls the printf method to simply printout the argument held in the list, but the output is like so:
this is a
string
As you can see, it contains a new line. Any ideas why?
Edit:
changing the line printf("%s", va_arg(args, char*)) to write(1, va_arg(args, char*), 6); produces the expected behavior. Is this an issue with the interaction between write and printf?
Edit 2:
See the answer below!