2011-08-11 17 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

あなたはファイルから読み込んだ番号をいくつかの永久記憶装置に保存すればよいのです!また、個々の数値を解析してその数値表現を取得したいと思うかもしれません。したがって、3つのステップ:

  1. 数字を保持するメモリを割り当てます。配列の配列は、便利なコンセプトのように見えます。数字の各ブロックに1つの配列があります。

  2. strtokを使用して、各行をそれぞれ1つの数字に対応する文字列にトークン化します。

  3. atoiまたはstrtolを使用して各数値を整数に解析します。

ここでは、始めるためにいくつかのサンプルコードです:

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

です。 'p!= NULL 'と' realloc'が 'NULL'を返すとコードがリークするので' p = realloc(p、sz) 'はある種のアンチパターンです。おそらくここではそれほど重要ではないでしょう。 – user786653

関連する問題