0

如何从具有如下结构的文件中读取数据到 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;    
}

谢谢你。

4

2 回答 2

3

没有人会为您编写代码。但这里有一个标准库函数列表,您可能需要这些函数来实现这一点:

  • fopen()
  • fscanf()
  • fclose()
  • malloc()
  • free()
于 2011-01-25T20:56:10.047 回答
0

从第 20 页开始的C 语言数字食谱的描述将向您展示一种分配内存的方法。将二维数组视为指向矩阵行的指针数组。

解析文件中的行是通过fopen()并可能fscanf()提取数字来完成的。

于 2011-01-25T21:01:41.600 回答