2017-06-18 151 views
0

我有一個名爲Members.txt .txt文件包含:如何將一個.txt文件逐行讀入C數組?

2 
Rebaz salimi 3840221821 0918888888 
Hojjat Qolami 2459816431 09177777777 

我寫了一個C文件讀入Members.txt陣列char w[100];像:

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循環之外。我只是更新代碼測試,如果它的工作.. – 2017-06-18 14:32:53