get_file_lines.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "get_file_lines.h"
  2. #include <talloc/talloc.h>
  3. #include <string/string.h>
  4. #include <noerr/noerr.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <err.h>
  10. #include <dirent.h>
  11. static void *grab_fd(const void *ctx, int fd)
  12. {
  13. int ret;
  14. unsigned int max = 16384, size = 0;
  15. char *buffer;
  16. buffer = talloc_array(ctx, char, max+1);
  17. while ((ret = read(fd, buffer + size, max - size)) > 0) {
  18. size += ret;
  19. if (size == max)
  20. buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
  21. }
  22. if (ret < 0) {
  23. talloc_free(buffer);
  24. buffer = NULL;
  25. } else
  26. buffer[size] = '\0';
  27. return buffer;
  28. }
  29. /* This version adds one byte (for nul term) */
  30. static void *grab_file(const void *ctx, const char *filename)
  31. {
  32. int fd;
  33. char *buffer;
  34. if (streq(filename, "-"))
  35. fd = dup(STDIN_FILENO);
  36. else
  37. fd = open(filename, O_RDONLY, 0);
  38. if (fd < 0)
  39. return NULL;
  40. buffer = grab_fd(ctx, fd);
  41. close_noerr(fd);
  42. return buffer;
  43. }
  44. char **get_file_lines(void *ctx, const char *name, unsigned int *num_lines)
  45. {
  46. char *buffer = grab_file(ctx, name);
  47. if (!buffer)
  48. err(1, "Getting file %s", name);
  49. return strsplit(buffer, buffer, "\n", num_lines);
  50. }