如何从具有如下结构的文件中读取数据到 C 中的多维整数数组中?
文件:
3 4 30 29
23 43 4 43
我需要使用动态分配将它放在“int** 矩阵”变量中。
更新:
我想要一个示例代码,我可以查看并研究下面列出的功能之间的关系:
- 多维数组及其与指针的关系;
- 内存的动态分配及其使用的一些解释;
- 如何处理来自我们不知道大小的外部源的数据,如何将行/列分隔到 C 程序内部的数组中。
共享代码:
int** BuildMatrixFromFile(char* infile, int rows, int cols){
FILE *fpdata; // deal with the external file
int** arreturn; // hold the dynamic array
int i,j; // walk thru the array
printf("file name: %s\n\n", infile);
fpdata = fopen(infile, "r"); // open file for reading data
arreturn = malloc(rows * sizeof(int *));
if (arreturn == NULL)
{
puts("\nFailure trying to allocate room for row pointers.\n");
exit(0);
}
for (i = 0; i < rows; i++)
{
arreturn[i] = malloc(cols * sizeof(int));
if (arreturn[i] == NULL)
{
printf("\nFailure to allocate for row[%d]\n",i);
exit(0);
}
for(j=0;j<cols;++j)
fscanf(fpdata, "%d", &arreturn[i][j]);
}
fclose(fpdata); // closing file buffer
return arreturn;
}
谢谢你。