#include <stdlib.h>
#include <stdio.h>
#include <tce/syscall.h>
void fprint(FILE f, char *s) {
write(f, 0, strlen(s), s);
}
void fprint_int(FILE f, int number) {
if (number == 0) {
fprint(f, "0");
return;
}
int negative = 0;
if (number < 0) {
negative = 1;
number = 0 - number;
}
int order = 0, temp = number, i;
char numbers[] = "0123456789";
while (temp > 0) {
order++;
temp /= 10;
}
char s[32], *r;
if (negative) {
s[0] = '-';
r = s + 1;
} else {
r = s;
}
for (i = order; i > 0; i--) {
r[i - 1] = numbers[number % 10];
number /= 10;
}
r[order] = 0;
fprint(f, s);
}
void fprint_hex(FILE f, unsigned v) {
char s[11] = {'0', 'x', 0};
int i;
char hexdigits[] = "0123456789ABCDEF";
for (i = 0; i < 8; i++) {
s[i + 2] = (hexdigits[v >> 28]);
v = v << 4;
}
s[11] = 0;
fprint(f, s);
}
void fprintf(FILE f, char* format, ...) {
va_list ap;
va_start(ap, format);
char* start = format;
while (*format) {
if (*format == '%') {
if (start != format) write(f, 0, format - start, start);
format++;
if (*format == 'd' || *format == 'i') {
fprint_int(f, va_arg(ap, int));
} else if (*format == 'p') {
fprint_hex(f, va_arg(ap, uint32_t));
} else if (*format == 's') {
fprint(f, va_arg(ap, char*));
}
format++;
start = format;
} else {
format++;
}
}
if (start != format) write(f, 0, format - start, start);
va_end(ap);
}
char* freadln(FILE f) {
int i;
char *p = (char*)malloc(256);
char *b = p;
while (1) {
int l = read(f, 0, 255, b);
if (l < 0) {
free(b);
return 0;
}
for (i = 0; i < l; i++) {
if (b[i] == '\n') {
b[i+1] = 0;
return p;
}
}
int d = b - p + l;
char* newp = (char*)malloc(d + 256);
memcpy(newp, p, d);
free(p);
p = newp;
b = p + d;
}
}