2017-06-18 91 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