就像在主题中一样,我试图逐行读取文件,但程序没有完成我想要的操作。因此,我试图检查结尾是否有,如果没有,行的空间不够,所以我重新分配它,并将行的位置->放在旧的长度上,以便连接下一个将被读取的内容:
int max_line_len = 10000;
int line_pos = 0;
char *line;
line = malloc(sizeof(char)*max_line_len);
while (fgets(&line[line_pos], max_line_len, file) != NULL) {
int line_length = strlen(line);
if (line[line_length - 1] == 'n') {
// do something to the lines
line_pos = 0;
} else {
max_line_len *= 2;
line_pos = line_length;
line = realloc(sizeof(char) * max_line_len);
}
}
}
fclose(file);
free(line);
但在realloc之后,一整行都没有被读取,他一直在输入(其他部分
fgets
读取过多。在第一个realloc
之后,line_pos
为9999,max_line_len
为20000,这意味着您最终将读取索引9999。。29999,而line
的最后一个有效索引只有19999。