2011-08-11 136 views
0

這很可能是一個愚蠢的問題! 我有一個文本文件填充隨機數,我想讀這些數字到一個數組。C - 從文本文件中讀取多行文件

我的文本文件看起來像這樣:

1231231 123213 123123 
1231231 123213 123123 
0 

1231231 123213 123123 
1231231 123213 123123 
0 

等等..這件作品numberse與0

結束。這是我到目前爲止已經試過:

FILE *file = fopen("c:\\Text.txt", "rt"); 
char line[512]; 

if(file != NULL) 
{ 
    while(fgets(line, sizeof line, file) != NULL) 
    { 
     fputs(line, stdout); 
    } 
    fclose(file); 
} 

這顯然不起作用,因爲我將每行讀入同一個變量。

我該如何讀取這些行以及何時該行獲取以0結尾的行,然後將該文本存儲到數組中?

所有幫助表示讚賞。

+0

所以,你要一個字符串數組? – cnicutar

+0

@cnicutar - 是 – Lars

+0

@Lars:你想要的是文本字符串,而不是實數? –

回答

1

您只需將您從文件中讀取的數字存儲在某個永久存儲器中!此外,你可能想分析個人數字並獲得他們的數字表示。所以,三個步驟:

  1. 分配一些內存來保存數字。一個數組數組看起來像一個有用的概念,每個數字塊都有一個數組。

  2. 使用strtok將每行標記爲對應於每個數字的字符串。

  3. 使用atoistrtol將每個數字解析爲一個整數。

下面是一些示例代碼,讓你開始:

FILE *file = fopen("c:\\Text.txt", "rt"); 
char line[512]; 

int ** storage; 
unsigned int storage_size = 10; // let's start with something simple 
unsigned int storage_current = 0; 

storage = malloc(sizeof(int*) * storage_size); // later we realloc() if needed 

if (file != NULL) 
{ 
    unsigned int block_size = 10; 
    unsigned int block_current = 0; 

    storage[storage_current] = malloc(sizeof(int) * block_size); // realloc() when needed 

    while(fgets(line, sizeof line, file) != NULL) 
    { 
     char * tch = strtok (line, " "); 
     while (tch != NULL) 
     { 
      /* token is at tch, do whatever you want with it! */ 

      storage[storage_current][block_current] = strtol(tch, NULL); 

      tch = strtok(NULL, " "); 

      if (storage[storage_current][block_current] == 0) 
      { 
       ++storage_current; 
       break; 
      } 

      ++block_current; 

      /* Grow the array "storage[storage_current]" if necessary */ 
      if (block_current >= block_size) 
      { 
       block_size *= 2; 
       storage[storage_current] = realloc(storage[storage_current], sizeof(int) * block_size); 
      } 
     } 

     /* Grow the array "storage" if necessary */ 
     if (storage_current >= storage_size) 
     { 
      storage_size *= 2; 
      storage = realloc(storage, sizeof(int*) * storage_size); 
     } 
    } 
} 

最後,你需要釋放內存:

for (unsigned int i = 0; i <= storage_current; ++i) 
    free(storage[i]); 
free(storage); 
+0

我認爲你需要's/int/storage/g'在幾個地方。 – user786653

+0

@user:是的,發現已經 - 謝謝! 'realloc'移動現有的內存嗎? –

+1

它的確如此。有一點需要注意的是'realloc'是'p = realloc(p,sz)'是一種反模式,因爲如果p!= NULL且'realloc'返回NULL,代碼將會泄漏。儘管這可能不會有太大影響。 – user786653