如何将数据从具有如下结构的文件中读取到C中的多维整数数组中?
文件:
3 4 30 29
23 43 4 43我需要使用动态分配将其放入"int**矩阵“变量中。
更新:
我想要一个示例代码,我可以查看并研究下面列出的功能之间的关系:
共享代码:
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;
}谢谢。
发布于 2011-01-25 21:01:41
从第20页开始的描述将向您展示分配内存的一种方法。将2d数组视为指向矩阵行的指针数组。
解析文件中的行是用fopen()和fscanf()完成的,以提取数字。
发布于 2011-01-25 20:56:10
没人会给你写代码。但是,下面列出了实现这一目标可能需要的标准库函数:
fopen()fscanf()fclose()malloc()free()https://stackoverflow.com/questions/4798618
复制相似问题