在 C 语言中,如何将具有如下结构的文件中的数据读取到多维整数数组中?
文件:
3 4 30 29
23 43 4 43
我需要使用动态分配将其放入“int** 矩阵”变量中。
更新:
我想要一个示例代码,我可以查看它并研究下面列出的功能之间的关系:
- 多维数组及其与指针到指针的关系;
- 内存的动态分配及其使用的一些解释;
- 如何处理来 self 们不知道其大小的外部源的数据,如何在 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;
}
谢谢。
最佳答案
没有人会为您编写代码。但这里是您可能需要实现此目的的标准库函数列表:
fopen()
fscanf()
fclose()
malloc()
free()
关于c - 在 C 中使用动态分配将文件读入多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4798618/