C动态内存分配 - 从文件中读取数据

时间:2012-04-04 16:40:50

标签: c dynamic-memory-allocation fgets calloc

我正在从MATLAB复制load()函数,以便在C应用程序中使用。我无法动态加载数据并初始化我需要的数组。更具体地说,我试图将fgets与已经使用calloc初始化的数组一起使用,我无法使其工作。功能如下,感谢帮助。

编辑:更新后的代码低于以下有缺陷的示例。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

void *load(const char *Filename);

void *load(const char *Filename)
{
    FILE* FID;
    if ((FID = fopen(Filename, "r")) == NULL)
    {
        printf("File Unavailable.\n");
    }
    else
    {
        int widthCount = 0, heightCount = 0;

        char ReadVal;
        while ((ReadVal = fgetc(FID)) != '\n')
        {
            if (ReadVal == ' ' || ReadVal == ',' || ReadVal == '\t')
            {
                widthCount++;
            }
        }

        rewind(FID);
        char* String = calloc(widthCount * 100, sizeof(char));
        while (fgets(*String, widthCount+1, FID) != EOF)
        {
            heightCount++;
        }
        double* Array = calloc(widthCount * heightCount, sizeof(double));
        rewind(FID);
        int i = 0, j = 0;
        char * pch;
        while (fgets(*String, widthCount+1, FID) != EOF)
        {
            pch = strtok(String, " ,\t");
            while (pch != NULL)
            {
                Array[i][j] = strtod(pch, NULL);
                pch = strtok (NULL, " ,\t");
                j++;
            }
            i++;
            j = 0;
        }

        fclose(FID);
        return Array;

    }

}

修订后的代码: 对于任何处理类似问题的人来说,此解决方案都有效。

void *load(const char *Filename)
{
    FILE* FID;
    if ((FID = fopen(Filename, "r")) == NULL)
    {
        printf("File Unavailable.\n");
        return NULL;
    }
    else
    {   
        int widthCount = 0, heightCount = 0;
        double *Array;
        char Temp[100];
        while ((Temp[0] = fgetc(FID)) != '\n')
        {
            if (Temp[0] == '\t' || Temp[0] == ' ' || Temp[0] == ',')
            {
                widthCount++;
            }
        }
        widthCount++;
        //printf("There are %i columns\n", widthCount);
        rewind(FID);
        while (fgets(Temp, 99, FID) != NULL)
        {
            heightCount++;
        }
        //printf("There are %i rows\n", heightCount);
        Array = (double *)calloc((widthCount * heightCount), sizeof(double));
        rewind(FID);
        int i = 0;
        while (!feof(FID))
        {

            fscanf(FID, "%lf", &*(Array + i));
            fgetc(FID);
            i++;
        }

        return Array;   
    }
}

1 个答案:

答案 0 :(得分:2)

数组不是2d数组而不是Array[i][j] = strtod(pch, NULL);只是递增指针*(Array++) = strtod(pch, NULL);