Skip to content

Commit 396ebe2

Browse files
committed
Fix read file lines implementation
Fix #21
1 parent a9556e9 commit 396ebe2

1 file changed

Lines changed: 23 additions & 21 deletions

File tree

src/common/file_utils.c

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -32,31 +32,33 @@
3232
#include "string_list.h"
3333

3434
char** apprun_read_lines(FILE* fp) {
35-
char** result = NULL;
36-
if (fp) {
37-
int c;
38-
39-
int line_count = 1;
40-
while ((c = fgetc(fp)) != EOF) {
41-
if (c == '\n')
42-
line_count++;
43-
}
35+
int array_len = 1024;
36+
int count = 0;
37+
char** result = apprun_string_list_alloc(array_len);
4438

45-
fseek(fp, 0, SEEK_SET);
46-
result = apprun_string_list_alloc(line_count + 1);
47-
char buf[1048576];
48-
for (int i = 0; i < line_count; i++) {
49-
fgets(buf, 1048576, fp);
50-
51-
// remove new line char if present
52-
unsigned len = strlen(buf);
53-
if (len > 0 && buf[len - 1] == '\n')
54-
buf[len - 1] = 0;
55-
56-
result[i] = strdup(buf);
39+
if (fp) {
40+
size_t len = 0;
41+
ssize_t read;
42+
43+
while ((read = getline(&result[count], &len, fp)) != -1) {
44+
if (read > 0 && result[count][read - 1] == '\n')
45+
result[count][read - 1] = 0;
46+
count++;
47+
if (count == array_len) {
48+
array_len = array_len * 2;
49+
char** old_array = result;
50+
51+
result = apprun_string_list_alloc(array_len);
52+
for (int i = 0; i < count; i++)
53+
result[i] = old_array[i];
54+
55+
free(old_array);
56+
}
5757
}
5858
}
5959

60+
result[count] = NULL;
61+
6062
return result;
6163
}
6264

0 commit comments

Comments
 (0)