免责声明:我是 C 的新手。
将 .txt 文件(也可以是其他文件类型)中的每一行转换为动态 calloc() 数组的最佳方法是什么,反之亦然?
在我的文件中,我必须遵循:
1 Hello
2 18
3 World
4 15
etc...
我想要这样的数组:
[0] Hello
[1] 18
[2] World
[3] 15
etc...
我现在的代码:
FILE *file;
file = fopen("test.txt", "r");
int i = 0;
//make dynamic calloc array
//while line!= EOF
//put line[i] into array
//i++
//realloc array, size +1
fclose(file);
这种方法好还是有更好的方法? 如果有人可以在代码方面帮我一点忙,我将不胜感激。
最佳答案
你接近正确的解决方案,但在这里你每次有一个新行时都重新分配动态数组,你可以做的是在数组中提前分配 N
字节并每次都用这个大小重新分配,这将避免数组和系统调用的频繁内存移动:
FILE *file;
file = fopen("test.txt", "r");
int i = 0;
int max = 256;
int resize = 512;
char **arr = malloc(max * sizeof(*arr));
//make dynamic calloc array
//while line!= EOF
//put line[i] into array
//i++
if(i == max)
realloc array, size + reisze;
fclose(file);
关于c - 文件到c中的动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41779390/