我想将文本文件中的数据存储到char**中。
.txt文件:
第一行
第二行
。。。。
现在我想打印这样的第二行:
printf("%s", lines[1]);
到目前为止,这是我的代码,但这里出了什么问题?
char* line = malloc(1000);
char** lines = malloc(10000);
FILE *file = fopen(file_path, "r");
int i = 0;
while(fgets(line, 1000, file) != NULL)
{
lines[i] = line;
printf("%s", line);
i++;
}
free(line);
常见的方法是将每一行一致地读取到同一缓冲区中,并将该行的副本存储在行数组中:
char line[1000]
int i = 0, nlines = 10000;
char **lines = malloc(nlines * sizeof(*lines));
while (fgets(line, sizeof(line), file) != NULL) {
if (i == nlines) { // must alloc more lines
nlines *= 2;
char **tmp = realloc(lines, nlines);
if (tmp == NULL) {
perror("Memory allocation error in realloc");
break;
}
lines = tmp;
}
lines[i] = strdup(line);
if (NULL == lines[i]) {
perror("Memory allocation error in strdup");
break;
}
++i;
}
如果您有足够的可用内存,上面的代码将接受您想要的任意行,或者如果无法再分配内存,则会停止,但仍然保留此时读取的内容。
主要限制是它将拆分长度超过998个字符的行(+换行符和终止null(