Advertisement
cd62131

join stdin

Jan 27th, 2019
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. static char *build_format(int bufsiz) {
  5.   char *format = calloc(1, bufsiz);
  6.   if (!format) {
  7.     exit(1);
  8.   }
  9.   sprintf(format, "%%%d[^\n]%%*c", bufsiz - 1);
  10.   return format;
  11. }
  12. static char *read_to(char **buf, int bufsiz) {
  13.   char *format = build_format(bufsiz);
  14.   *buf = calloc(1, bufsiz);
  15.   int n = scanf(format, *buf);
  16.   free(format);
  17.   if (n != 1) {
  18.     free(*buf);
  19.     return NULL;
  20.   }
  21.   return *buf;
  22. }
  23. static char *append_to(char **acc, char *s) {
  24.   *acc = realloc(*acc, strlen(*acc) + strlen(s) + 1);
  25.   if (!*acc) {
  26.     exit(1);
  27.   }
  28.   strcat(*acc, s);
  29.   return *acc;
  30. }
  31. int main(void) {
  32.   char *acc = calloc(1, 1);
  33.   *acc = '\0';
  34.   for (char *buf = NULL; read_to(&buf, BUFSIZ); free(buf)) {
  35.     if (*buf == ',') {
  36.       free(buf);
  37.       break;
  38.     }
  39.     append_to(&acc, buf);
  40.   }
  41.   printf("%s\n", acc);
  42.   free(acc);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement