Skip to content

Commit

Permalink
merge vfprintf & vsnprintf
Browse files Browse the repository at this point in the history
  • Loading branch information
coolyjg committed Apr 29, 2023
1 parent f152cfe commit 0fea8aa
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 68 deletions.
4 changes: 2 additions & 2 deletions ulib/c_libax/include/stdbool.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

/* Represents true-or-false values */
#ifndef __cplusplus
#define true 1
#define true 1
#define false 0
#define bool _Bool
#define bool _Bool
#endif

#endif // __STDBOOL_H__
79 changes: 13 additions & 66 deletions ulib/c_libax/src/stdio.c
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ int vsnprintf(char *restrict buf, size_t size, const char *restrict fmt, va_list
s += 2;
}
buf[cnt] = '\0';
return 0;
return cnt;
}

int snprintf(char *restrict s, size_t n, const char *restrict fmt, ...)
Expand All @@ -410,74 +410,21 @@ int vsprintf(char *restrict s, const char *restrict fmt, va_list ap)
return vsnprintf(s, INT_MAX, fmt, ap);
}

/// Currently print formatted text to stdout.
/// Currently print formatted text to stdout or stderr.
/// TODO: print to file
int vfprintf(FILE *restrict _f, const char *restrict fmt, va_list ap)
int vfprintf(FILE *restrict f, const char *restrict fmt, va_list ap)
{
int l = 0;
char *a, *z, *s = (char *)fmt;
int ret;
char buf[1024];

for (;;) {
if (!*s)
break;
for (a = s; *s && *s != '%'; s++)
;
for (z = s; s[0] == '%' && s[1] == '%'; z++, s += 2)
;
l = z - a;
out(stdout->fd, a, l);
if (l)
continue;
if (s[1] == 0)
break;
switch (s[1]) {
case 'u':
printint(va_arg(ap, int), 10, 0);
break;
case 'c':
putchar((char)va_arg(ap, int));
break;
case 'd':
printint(va_arg(ap, int), 10, 1);
break;
case 'x':
printint(va_arg(ap, int), 16, 1);
break;
case 'p':
printptr(va_arg(ap, uint64_t));
break;
case 's':
if ((a = va_arg(ap, char *)) == 0)
a = "(null)";
l = strnlen(a, 200);
out(stdout->fd, a, l);
break;
case 'l':
if (s[2] == 'u')
printint(va_arg(ap, long), 10, 0);
else if (s[2] == 'd')
printint(va_arg(ap, long), 10, 1);
else if (s[2] == 'x')
printint(va_arg(ap, long), 16, 1);
else {
putchar('%');
putchar(s[1]);
if (s[2])
putchar(s[2]);
else
s -= 1;
}
s += 1;
break;
default:
// Print unknown % sequence to draw attention.
putchar('%');
putchar(s[1]);
break;
}
s += 2;
}
return 0;
ret = vsnprintf(buf, sizeof(buf), fmt, ap);
if (ret < 0)
return ret;

if (f->fd == stdout->fd || f->fd == stderr->fd)
out(f->fd, buf, sizeof(buf));

return ret;
}

int sprintf(char *restrict s, const char *restrict fmt, ...)
Expand Down

0 comments on commit 0fea8aa

Please sign in to comment.