grab_file.c 1.2 KB

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