grab_file.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "grab_file.h"
  2. #include <ccan/talloc/talloc.h>
  3. #include <ccan/noerr/noerr.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. void *grab_fd(const void *ctx, int fd, size_t *size)
  9. {
  10. int ret;
  11. size_t max, s;
  12. char *buffer;
  13. struct stat st;
  14. if (!size)
  15. size = &s;
  16. *size = 0;
  17. if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode))
  18. max = st.st_size;
  19. else
  20. max = 16384;
  21. buffer = talloc_array(ctx, char, max+1);
  22. while ((ret = read(fd, buffer + *size, max - *size)) > 0) {
  23. *size += ret;
  24. if (*size == max) {
  25. buffer = talloc_realloc(ctx, buffer, char, max*2+1);
  26. if (!buffer) {
  27. buffer = talloc_realloc(ctx, buffer, char,
  28. max + 1024*1024 + 1);
  29. if (!buffer)
  30. return NULL;
  31. max += 1024*1024;
  32. } else
  33. max *= 2;
  34. }
  35. }
  36. if (ret < 0) {
  37. talloc_free(buffer);
  38. buffer = NULL;
  39. } else
  40. buffer[*size] = '\0';
  41. return buffer;
  42. }
  43. void *grab_file(const void *ctx, const char *filename, size_t *size)
  44. {
  45. int fd;
  46. char *buffer;
  47. if (!filename)
  48. fd = dup(STDIN_FILENO);
  49. else
  50. fd = open(filename, O_RDONLY, 0);
  51. if (fd < 0)
  52. return NULL;
  53. buffer = grab_fd(ctx, fd, size);
  54. close_noerr(fd);
  55. return buffer;
  56. }