Program to generate an xml file based on a provided text file
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.7KB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include "main.h"
  6. #include "readfile.h"
  7. #include "encoding.h"
  8. #include "string.h"
  9. int readfile(CONFIG *config) {
  10. FILE *file = NULL;
  11. int start;
  12. int end;
  13. int i = 0;
  14. char *line = NULL;
  15. char **array = NULL;
  16. size_t n = 0;
  17. ssize_t nchr = 0;
  18. size_t idx = 0;
  19. size_t it = 0;
  20. size_t new_max = MAX_LINES;
  21. char *ch = strtok(config->chapter_numbers, "-");
  22. while (ch != NULL) {
  23. if (i == 0) {
  24. start = atoi(ch);
  25. i++;
  26. }
  27. else {
  28. end = atoi(ch);
  29. }
  30. ch = strtok(NULL, "-");
  31. }
  32. #ifdef DEBUG
  33. printf("Start chapter: %d\nEnd chapter: %d\n", start, end);
  34. #endif
  35. i = 0;
  36. file = fopen("Biblia.txt", "r");
  37. if (file == NULL) {
  38. perror("fopen");
  39. return 1;
  40. }
  41. if (!(array = calloc(new_max, sizeof(*array)))) {
  42. fprintf(stderr, "allocación de memoria falló.");
  43. return 1;
  44. }
  45. while ((nchr = getline(&line, &n, file)) != -1) {
  46. while (nchr > 0 && (line[nchr - 1] == '\n' || line[nchr - 1] == '\r' || line[nchr - 1] == ' ' || line[nchr - 1] == '\t')) {
  47. /* remove whitespace from end of the line */
  48. line[nchr--] = 0;
  49. }
  50. line[nchr] = '\0';
  51. array[idx++] = strdup(line);
  52. /* not enough memory for more lines, time to allocate more memory */
  53. if (idx == new_max) {
  54. new_max = new_max * 2;
  55. char **tmp = realloc(array, new_max * sizeof(*array));
  56. if (!tmp) {
  57. fprintf(stderr, "reallocación de memoria falló.");
  58. return 1;
  59. }
  60. array = tmp;
  61. }
  62. }
  63. /* free the extra unused memory */
  64. if (new_max > idx) {
  65. char **tmp = realloc(array, idx * sizeof(*array));
  66. if (!tmp) {
  67. fprintf(stderr, "reallocación de memoria falló.");
  68. return 1;
  69. }
  70. array = tmp;
  71. }
  72. if (file) {
  73. fclose(file);
  74. }
  75. if (line) {
  76. free(line);
  77. }
  78. printf ("\nLines in file:\n\n");
  79. for (it = 0; it < 20; it++) {
  80. line = latin2utf8(array[it]);
  81. /* printf(" array [%lu] %s\n", (long) it, line); */
  82. if (line != NULL) {
  83. if (strcmp(line, config->bible) == 0) {
  84. printf("Bible match: %d -> %s\n", (int) it + 1, line);
  85. }
  86. if (strcmp(line, config->book) == 0) {
  87. printf("Book match: %d -> %s\n", (int) it + 1, line);
  88. }
  89. }
  90. free(line);
  91. }
  92. for (it = 0; it < idx; it++) {
  93. free(array[it]);
  94. }
  95. free(array);
  96. return 0;
  97. }