2017-06-18 14 views
0

私は含まれていMembers.txtという名前の.txtファイルがあります:私が好きchar w[100];配列にMembers.txtを読み取るためにCファイルを書いていた.txtファイルを行単位でC配列に読み込む方法は?

2 
Rebaz salimi 3840221821 0918888888 
Hojjat Qolami 2459816431 09177777777 

を:

int main() 
{ 
     int i = 0, line = 5; 
     char w[100]; 
     char f[20]; 
     char k[15]; 
     FILE *myfile; 
         myfile = fopen("Members.txt","r"); 
         if (myfile== NULL) 
         { 
         printf("can not open file \n"); 
         return 1; 
         } 

    while(line--){ 
        fscanf(myfile,"%s",&w[i]); 
        i++; 
        printf("\n%s", &w[i]); 
        } 
        fclose(myfile); 
     return 0; 
} 

しかし、私はMembers.txtへのすべての改行を必要とします行ごとに異なる配列に保存することができます。

+1

代わりに何が起こるのですか。 – Yunnosch

+3

見てください[https://www.google.com/search?q=How+to+read+a+.txt+file + + + C +配列+ライン+バイ+ライン)。 – alk

+0

ファイルの最初の行にある '3'は何ですか? –

答えて

1

ファイルを読み込んで配列内に格納する場合のソリューションは次のとおりです。配列の内部には格納できませんが、配列の内部構造を格納できます。ここでは、100行のテキストファイルにアクセスできます。ここでは、とにかくコードです:

#include <stdio.h> 

//Use Structure to store more than one data type 
//Since your file not only consist of string, it also have int 
struct members 
{ 
    char a[100]; 
    char b[100]; 
    long long int c; 
    long long int d; 
}; 
//Here I make 100 line so that you can read 100 line of text file 
struct members cur_member[100]; 

int main(void) { 
    FILE *myfile = fopen("Members.txt", "r"); 
    if (myfile == NULL) { 
     printf("Cannot open file.\n"); 
     return 1; 
    } 
    else { 
     //Check for number of line 
      char ch; 
      int count = 0; 
     do 
     { 
     ch = fgetc(myfile); 
     if (ch == '\n') count++; 
     } while (ch != EOF); 
     rewind(myfile); 

     //Since you put 2 earlier in the member.txt we need to dump it 
     //so that it wont affect the scanning process 
     int temp; 
     fscanf(myfile, "%d", &temp); 
     printf("%d\n", temp); 
     //Now scan all the line inside the text 
     int i; 
     for (i = 0; i < count; i++) { 
      fscanf(myfile, "%s %s %lld %lld\n", cur_member[i].a, cur_member[i].b, &cur_member[i].c, &cur_member[i].d); 
      printf("%s %s %lld %lld\n", cur_member[i].a, cur_member[i].b, cur_member[i].c, cur_member[i].d); 
     } 
    } 
} 

は、これが結果です:

2 
Rebaz salimi 3840221821 918888888 
Hojjat Qolami 2459816431 9177777777 
Press any key to continue . . . 

このプログラムはあなたの現在のファイルを読み込みますし、私はちょうどそれが動作を示すために、それを印刷します。情報にアクセスしてファイルを編集することができます。 それはすべてです..

+1

'char ch;' - >> 'int ch;' – wildplasser

+0

@Joesあなたはこれらのエラーがあります: 1.error: 'for 'ループ初期宣言はC99またはC11モードでのみ許可されます。 2.エラー:入力の終了時に期待される宣言またはステートメント| – moh89

+0

'int i'をforループの外側に更新コードとして入れてみましょう。私はそれが動作する場合、私はちょうどコードテストを更新します。 –

関連する問題