generarxml/src/readfile.c

115 lines
2.8 KiB
C
Raw Normal View History

2016-10-16 14:16:03 -03:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "main.h"
#include "readfile.h"
#include "encoding.h"
#include "string.h"
int readfile(CONFIG *config) {
FILE *file = NULL;
int start;
int end;
int i = 0;
char *line = NULL;
char **array = NULL;
2016-10-16 17:49:48 -03:00
ssize_t chars = 0;
size_t lines = 0;
size_t j = 0;
2016-10-16 14:16:03 -03:00
size_t new_max = MAX_LINES;
char *ch = strtok(config->chapter_numbers, "-");
while (ch != NULL) {
if (i == 0) {
start = atoi(ch);
i++;
}
else {
end = atoi(ch);
}
ch = strtok(NULL, "-");
}
#ifdef DEBUG
printf("Start chapter: %d\nEnd chapter: %d\n", start, end);
#endif
i = 0;
file = fopen("Biblia.txt", "r");
if (file == NULL) {
perror("fopen");
return 1;
}
if (!(array = calloc(new_max, sizeof(*array)))) {
2016-10-16 17:49:48 -03:00
fprintf(stderr, "Allocación de memoria falló.");
2016-10-16 14:16:03 -03:00
return 1;
}
2016-10-16 17:49:48 -03:00
while ((chars = getline(&line, &j, file)) != -1) {
while (chars > 0 && (line[chars - 1] == '\n' || line[chars - 1] == '\r' || line[chars - 1] == ' ' || line[chars - 1] == '\t')) {
2016-10-16 14:16:03 -03:00
/* remove whitespace from end of the line */
2016-10-16 17:49:48 -03:00
chars--;
line[chars] = '\0';
2016-10-16 14:16:03 -03:00
}
2016-10-16 17:49:48 -03:00
line[chars] = '\0';
lines++;
array[lines] = strdup(line);
2016-10-16 14:16:03 -03:00
/* not enough memory for more lines, time to allocate more memory */
2016-10-16 17:49:48 -03:00
if (lines == new_max) {
2016-10-16 14:16:03 -03:00
new_max = new_max * 2;
char **tmp = realloc(array, new_max * sizeof(*array));
if (!tmp) {
2016-10-16 17:49:48 -03:00
fprintf(stderr, "Reallocación de memoria falló.");
2016-10-16 14:16:03 -03:00
return 1;
}
array = tmp;
}
}
/* free the extra unused memory */
2016-10-16 17:49:48 -03:00
if (new_max > lines) {
char **tmp = realloc(array, lines * sizeof(*array));
2016-10-16 14:16:03 -03:00
if (!tmp) {
2016-10-16 17:49:48 -03:00
fprintf(stderr, "Reallocación de memoria falló.");
2016-10-16 14:16:03 -03:00
return 1;
}
array = tmp;
}
if (file) {
fclose(file);
}
if (line) {
free(line);
}
2016-10-16 17:49:48 -03:00
for (j = 0; j < lines; j++) {
line = latin2utf8(array[j]);
/* printf(" array [%lu] %s\n", (long) j, line); */
2016-10-16 14:16:03 -03:00
if (line != NULL) {
if (strcmp(line, config->bible) == 0) {
2016-10-16 17:49:48 -03:00
#ifdef DEBUG
printf("Bible match: %lu -> %s\n", (long) j, line);
#endif
2016-10-16 14:16:03 -03:00
}
if (strcmp(line, config->book) == 0) {
2016-10-16 17:49:48 -03:00
#ifdef DEBUG
printf("Book match: %lu -> %s\n", (long) j, line);
#endif
2016-10-16 14:16:03 -03:00
}
}
free(line);
}
2016-10-16 17:49:48 -03:00
for (j = 0; j < lines; j++) {
free(array[j]);
2016-10-16 14:16:03 -03:00
}
free(array);
return 0;
}