如何逐行将.txt文件读入C数组?

时间:2017-06-18 10:10:33

标签: c arrays

我有一个名为Members.txt的.txt文件,其中包含:

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 个答案:

答案 0 :(得分: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 . . .

此程序将读取您当前的文件,我只需打印它,以显示它的工作原理。您可以访问该信息并编辑该文件。 多数民众赞成......