123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- #include <stdio.h>
- #include <stdlib.h>
- #define SIZE 9
- typedef struct {
- char *buf;
- int size;
- int place;
- } catbuf;
- int append(catbuf *b, char *s);
- int main(void) {
- char buf[SIZE];
- buf[0] = '\0';
-
- catbuf b = (catbuf){ .buf = buf, .size = SIZE, .place = 0 };
-
- if(append(&b, "foo")) { puts("FAIL"); return 0; }
- if(append(&b, "bar")) { puts("FAIL"); return 0; }
-
- puts(buf);
- }
- int append(catbuf *b, char *s) {
- int i;
- // i:0 1 2
- // -------- . . .
- // [ | | | | | | | | | ]
- // 0 1 2 3 4 5 6 7 8 9
- // size = 9
- // place = 4
- // place is amount used
- // size is amount available
- // we need 1 extra space for '\0'
- for(i = b->place; *s; i++) {
- if(i + 1 >= b->size) {
- // Can replace this with a realloc if you wanted
- // dynamically increasing buffer
- b->buf[i] = '\0';
- b->place = i;
- return -1;
- }
- b->buf[i] = *s;
- s++;
- }
- b->buf[i] = '\0';
- b->place = i;
-
- return 0;
- }
|