1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
struct vd_cookie {
int fd;
char *buffer;
uint8_t buf_len;
uint8_t buf_used;
int sent_bytes;
};
size_t min(size_t a, size_t b) { return (a < b) ? a : b; }
size_t vd_write(FILE *f, const unsigned char *s, size_t l) {
struct vd_cookie *c = f->cookie;
int clear_buffer = 0;
size_t b_copy = min(l, c->buf_len - (c->buf_used));
for (int i = 0; i < b_copy; i++) {
c->buffer[c->buf_used + i] = s[i];
if (s[i] == '\n')
clear_buffer = 1;
}
c->buf_used += b_copy;
if (clear_buffer) {
int rc = write(c->fd, c->buffer, c->buf_used);
c->buf_used = 0;
if (-1 == rc) {
return (size_t)-1;
}
c->sent_bytes += rc;
}
return l;
}
int vdprintf(int fd, const char *format, va_list ap) {
FILE f = {
.write = write_fd,
.fd = fd,
};
return vfprintf(&f, format, ap);
// return -1;
/*
char buffer[32];
struct vd_cookie c = {.fd = fd,
.buffer = buffer,
.buf_len = 32,
.buf_used = 0,
.sent_bytes = 0};
FILE f = {
.write = vd_write,
.cookie = &c,
};
// If an output error was encountered, these functions shall return a
// negative value and set errno to indicate the error.
if (-1 == vfprintf(&f, format, ap))
return -1;
// Upon successful completion, the dprintf(),
// fprintf(), and printf() functions shall return the number of bytes
// transmitted.
if(0 == c.buf_used)
return c.sent_bytes;
// First the current buffer needs to be cleared
int rc = write(fd, buffer, c.buf_used);
if (-1 == rc) {
return -1;
}
c.sent_bytes += rc;
return c.sent_bytes;*/
}
|