daily pastebin goal
62%
SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 69 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct buffer
  2. {
  3.     int begin, end, size;
  4.     char *buf;
  5. };
  6. typedef struct buffer buffer;
  7. buffer* create_buffer(int size)
  8. {
  9.     buffer *b = (buffer *)calloc(1, sizeof(*b));
  10.     b->begin = b->end = 0;
  11.     b->size = size;
  12.     b->buf = (char *)calloc(size, sizeof(b->buf[0]));
  13.     return b;
  14. }
  15. void write_buffer(buffer *b, void *data, int size)
  16. {
  17.     char *d = (char *)data;
  18.     for (int i = 0; i < size && b->begin != (b->end + 1) % b->size; ++i)
  19.     {
  20.         b->buf[b->end] = d[i];
  21.         b->end = (b->end + 1) % b->size;
  22.     }
  23. }
  24. void read_buffer(buffer *b, void *data, int size)
  25. {
  26.     char *d = (char *)data;
  27.     for (int i = 0; i < size && b->begin != b->end; ++i)
  28.     {
  29.         d[i] = b->buf[b->begin];
  30.         b->begin = (b->begin + 1) % b->size;
  31.     }
  32. }
  33. int main(void)
  34. {
  35.     buffer* b = create_buffer(10);
  36.     char s[] = "asdasd";
  37.     char s2[] = "qweqwerty";
  38.     write_buffer(b, s, sizeof(s));
  39.     write_buffer(b, s2, sizeof(s2));
  40.     char s3[100];
  41.     read_buffer(b, s3, sizeof(s3));
  42.     for (int i = 0; i < 10; ++i)
  43.         printf("%c", s3[i]);
  44.     return 0;
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top