get_file_lines.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. /* This is a dumb one which copies. We could mangle instead. */
  45. static char **split(const void *ctx, const char *text, const char *delims,
  46. unsigned int *nump)
  47. {
  48. char **lines = NULL;
  49. unsigned int max = 64, num = 0;
  50. lines = talloc_array(ctx, char *, max+1);
  51. while (*text != '\0') {
  52. unsigned int len = strcspn(text, delims);
  53. lines[num] = talloc_array(lines, char, len + 1);
  54. memcpy(lines[num], text, len);
  55. lines[num][len] = '\0';
  56. text += len;
  57. text += strspn(text, delims);
  58. if (++num == max)
  59. lines = talloc_realloc(ctx, lines, char *, max*=2 + 1);
  60. }
  61. lines[num] = NULL;
  62. if (nump)
  63. *nump = num;
  64. return lines;
  65. }
  66. char **get_file_lines(void *ctx, const char *name, unsigned int *num_lines)
  67. {
  68. char *buffer = grab_file(ctx, name);
  69. if (!buffer)
  70. err(1, "Getting file %s", name);
  71. return split(buffer, buffer, "\n", num_lines);
  72. }