-
Notifications
You must be signed in to change notification settings - Fork 14
/
read_write_both.c
60 lines (43 loc) · 1.3 KB
/
read_write_both.c
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
// This examples demonstrates dynamic objects of multiple interfaces.
#include <interface99.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define Reader_IFACE vfunc(size_t, read, VSelf, char *dest, size_t bytes_to_read)
interface(Reader);
#define Writer_IFACE vfunc(size_t, write, VSelf, const char *src, size_t bytes_to_write)
interface(Writer);
#define ReadWriter_IFACE
#define ReadWriter_EXTENDS (Reader, Writer)
interface(ReadWriter);
typedef struct {
FILE *fp;
} File;
size_t File_read(VSelf, char *dest, size_t bytes_to_read) {
VSELF(File);
return fread(dest, 1, bytes_to_read, self->fp);
}
impl(Reader, File);
size_t File_write(VSelf, const char *src, size_t bytes_to_write) {
VSELF(File);
return fwrite(src, 1, bytes_to_write, self->fp);
}
impl(Writer, File);
// `Reader` and `Writer` are already implemented.
impl(ReadWriter, File);
/*
* Output:
* We have read: 'hello world'
*/
int main(void) {
FILE *fp = tmpfile();
assert(fp);
ReadWriter rw = DYN_LIT(File, ReadWriter, {fp});
VCALL_SUPER(rw, Writer, write, "hello world", strlen("hello world"));
rewind(fp);
char hello_world[16] = {0};
VCALL_SUPER(rw, Reader, read, hello_world, strlen("hello world"));
printf("We have read: '%s'\n", hello_world);
fclose(fp);
return 0;
}