免责声明:我是C的新手。
将.txt文件(也可以是其他文件类型)中的每一行转换为dinamic 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
在数组中预先分配字节,然后每次以此大小重新分配,这样可以避免频繁数组和sys调用的内存移动:
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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句