2012-04-04 95 views
2

我正在從MATLAB複製load()函數以用於C應用程序。我無法動態加載數據並初始化我需要的數組。更具體地說,我試圖用已經用calloc初始化的數組使用fgets,但我無法使它工作。該功能如下,並感謝幫助。C動態內存分配 - 從文件讀取數據

編輯:更新的代碼是以下有缺陷的示例。

#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; 
    } 
} 

回答

2

數組是不是二維數組,而不是僅僅Array[i][j] = strtod(pch, NULL);遞增指針*(Array++) = strtod(pch, NULL);

+0

謝謝,我沒有抓到這一點。我的主要問題是越過fgets命令。我需要能夠根據我在運行時確定的行大小抓取每一行。 – 2012-04-04 16:44:40

+0

@NathanTornquist它可能有助於給出一個文件格式的示例,線寬如何設置etvc – 2012-04-04 16:46:26

+0

我沒有線寬。對於課堂,目標是讓用戶提供要加載的數據的維度。我決定嘗試加載所有沒有任何這些值的數據。這就是函數開始處的寬度和高度計數的目的。 – 2012-04-04 16:48:38