我正在从 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;
}
}