moh89
moh89

Reputation: 132

How to read a .txt file into C array line by line?

i have a .txt file named Members.txt which contain:

2
Rebaz salimi 3840221821 0918888888
Hojjat Qolami 2459816431 09177777777

i had written a C file to read Members.txt into char w[100]; array like:

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;
}

but ,i need every newline ofMembers.txt to be saved into different array line by line.

Upvotes: 2

Views: 19392

Answers (1)

user8017372
user8017372

Reputation:

Here is the solution if you want to read the file and store inside array, You cannot store inside array, but you can store inside structure of array. Here I make you can access 100 lines of text file. Here is the code anyway:

#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);
        }
    }
}

And this is the result:

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

This program will read your current file and I just print it, to show it works. You can access the information and edit the file. Thats all..

Upvotes: 1

Related Questions