main.c 960 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define SIZE 9
  4. typedef struct {
  5. char *buf;
  6. int size;
  7. int place;
  8. } catbuf;
  9. int append(catbuf *b, char *s);
  10. int main(void) {
  11. char buf[SIZE];
  12. buf[0] = '\0';
  13. catbuf b = (catbuf){ .buf = buf, .size = SIZE, .place = 0 };
  14. if(append(&b, "foo")) { puts("FAIL"); return 0; }
  15. if(append(&b, "bar")) { puts("FAIL"); return 0; }
  16. puts(buf);
  17. }
  18. int append(catbuf *b, char *s) {
  19. int i;
  20. // i:0 1 2
  21. // -------- . . .
  22. // [ | | | | | | | | | ]
  23. // 0 1 2 3 4 5 6 7 8 9
  24. // size = 9
  25. // place = 4
  26. // place is amount used
  27. // size is amount available
  28. // we need 1 extra space for '\0'
  29. for(i = b->place; *s; i++) {
  30. if(i + 1 >= b->size) {
  31. // Can replace this with a realloc if you wanted
  32. // dynamically increasing buffer
  33. b->buf[i] = '\0';
  34. b->place = i;
  35. return -1;
  36. }
  37. b->buf[i] = *s;
  38. s++;
  39. }
  40. b->buf[i] = '\0';
  41. b->place = i;
  42. return 0;
  43. }