stash.c 970 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include <stdio.h>
  2. #define BUFSIZE 1024
  3. #define NODESIZE (BUFSIZE*10)
  4. struct node {
  5. struct node *next;
  6. char buf[NODESIZE];
  7. }
  8. main(argc, argv)
  9. int argc;
  10. char **argv;
  11. {
  12. char stash[BUFSIZE];
  13. int n, f, lsize;
  14. struct node *head, *last, *malloc();
  15. head = last = malloc(sizeof (struct node));
  16. head->next = NULL;
  17. lsize = 0;
  18. while ((n = read(0, stash, BUFSIZE)) > 0) {
  19. if (lsize+n > NODESIZE) {
  20. int t = NODESIZE - lsize;
  21. strncpy(&last->buf[lsize], stash, t);
  22. if ((last->next = malloc(sizeof(struct node))) == NULL) {
  23. printf("stash: not enough memory\n");
  24. exit(1);
  25. }
  26. last = last->next;
  27. strncpy(last->buf, &stash[t], n-t);
  28. lsize = n-t;
  29. } else {
  30. strncpy(&last->buf[lsize], stash, n);
  31. lsize += n;
  32. }
  33. }
  34. if (argc < 2)
  35. f = 1;
  36. else if ((f = creat(argv[1], 0666)) < 0) {
  37. perror(argv[1]);
  38. exit (1);
  39. }
  40. for (; head->next != NULL; head = head->next)
  41. write(f, head->buf, NODESIZE);
  42. write(f, head->buf, lsize);
  43. exit (0);
  44. }