From: Francois Fleuret Date: Tue, 9 Aug 2011 11:24:22 +0000 (+0200) Subject: Replaced a big spaghetti mess with fgets. X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?a=commitdiff_plain;h=adeac87e367824af309c8bafc0010cbe42d09c6f;p=selector.git Replaced a big spaghetti mess with fgets. --- diff --git a/selector.c b/selector.c index ed30692..9b88799 100644 --- a/selector.c +++ b/selector.c @@ -781,7 +781,7 @@ void read_file(struct hash_table_t *hash_table, int nb_lines_max, int *nb_lines, char **lines) { char raw_line[BUFFER_SIZE]; - int start, end, eol, k; + char *s; FILE *file; file = fopen(input_filename, "r"); @@ -791,51 +791,11 @@ void read_file(struct hash_table_t *hash_table, exit(EXIT_FAILURE); } - start = 0; - end = 0; - - while(*nb_lines < nb_lines_max && (end > start || !feof(file))) { - eol = start; - - /* Look for the end of a line in what is already in the buffer */ - while(eol < end && raw_line[eol] != '\n') eol++; - - /* if we did not find the of a line, move what has not been - processed and is in the buffer to the beginning of the buffer, - fill the buffer with new data from the file, and look for the - end of a line */ - if(eol == end) { - for(k = 0; k < end - start; k++) { - raw_line[k] = raw_line[k + start]; - } - end -= start; - eol -= start; - start = 0; - end += fread(raw_line + end, sizeof(char), BUFFER_SIZE - end, file); - while(eol < end && raw_line[eol] != '\n') eol++; + while(*nb_lines < nb_lines_max && (fgets(raw_line, BUFFER_SIZE, file))) { + for(s = raw_line + strlen(raw_line) - 1; s > raw_line && *s == '\n'; s--) { + *s = '\0'; } - - /* The end of the line is the buffer size, which means the line is - too long */ - - if(eol == BUFFER_SIZE) { - raw_line[BUFFER_SIZE - 1] = '\0'; - fprintf(stderr, "selector: Line too long (max is %d characters):\n", - BUFFER_SIZE); - fprintf(stderr, "%s", raw_line); - fprintf(stderr, "\n"); - exit(EXIT_FAILURE); - } - - /* If we got a line, we replace the carriage return by a \0 to - finish the string */ - - raw_line[eol] = '\0'; - - store_line(hash_table, raw_line + start, - nb_lines, lines); - - start = eol + 1; + store_line(hash_table, raw_line, nb_lines, lines); } fclose(file);