Skip to content

Commit

Permalink
Fix read file lines implementation
Browse files Browse the repository at this point in the history
Fix #21
  • Loading branch information
azubieta committed Nov 3, 2020
1 parent a9556e9 commit 396ebe2
Showing 1 changed file with 23 additions and 21 deletions.
44 changes: 23 additions & 21 deletions src/common/file_utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -32,31 +32,33 @@
#include "string_list.h"

char** apprun_read_lines(FILE* fp) {
char** result = NULL;
if (fp) {
int c;

int line_count = 1;
while ((c = fgetc(fp)) != EOF) {
if (c == '\n')
line_count++;
}
int array_len = 1024;
int count = 0;
char** result = apprun_string_list_alloc(array_len);

fseek(fp, 0, SEEK_SET);
result = apprun_string_list_alloc(line_count + 1);
char buf[1048576];
for (int i = 0; i < line_count; i++) {
fgets(buf, 1048576, fp);

// remove new line char if present
unsigned len = strlen(buf);
if (len > 0 && buf[len - 1] == '\n')
buf[len - 1] = 0;

result[i] = strdup(buf);
if (fp) {
size_t len = 0;
ssize_t read;

while ((read = getline(&result[count], &len, fp)) != -1) {
if (read > 0 && result[count][read - 1] == '\n')
result[count][read - 1] = 0;
count++;
if (count == array_len) {
array_len = array_len * 2;
char** old_array = result;

result = apprun_string_list_alloc(array_len);
for (int i = 0; i < count; i++)
result[i] = old_array[i];

free(old_array);
}
}
}

result[count] = NULL;

return result;
}

Expand Down

0 comments on commit 396ebe2

Please sign in to comment.