I want to store my file data in array??

List.txt contains
Xyz Abc
Lmn Pqr
Hij Klm

#include <stdio.h>
#include<conio.h>

int main()
{
   FILE * pFile;
   char mystring [100];
    

   pFile = fopen ("c:\\List.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else
   {
          while(!feof(pFile)) 
          { 
              fgets (mystring , 100 , pFile);
              puts (mystring);
             
          }   
    
   }
   
    fclose (pFile);
   getch();
  
}

But i want to store each string in 2d matrix
like mat[0]=Xyz
mat[1]=Abc

How to do it??

well you would need two for loops for a 2D array..something like this

for(i=0;i<row;i++)
{
	cin>>array[i][0];
	for(j=0;j<col;j++)
	{	
		cin>>array[0][j];
	}
}

i'd advice you to use fstream for filehandling, it's easier to use and uses the same trusted << and >> ways of the iostream

Here is my file text file data

Tree Bush
Apple Mango
Animal Dog
Animal2 Cat

#include <stdio.h>
#include<conio.h>
#include<string>
#include<iostream>
#include<fstream>
using namespace std; 

int main()
{
   FILE * pFile;
   char mystring [100];
   char mystring2[100];
   char ch;
    
  int i=0,j=0;
                
   pFile = fopen ("c:\\List.txt" , "r");
   if (pFile == NULL) perror ("Error opening file");
   else
   {
      
          while(!feof(pFile)) 
          { 
                     
             while(getc(pFile)!=' ');
             {
              
               fgets (mystring , 20 , pFile);
               printf("\n");
                         
               puts (mystring);
              
                          
             }             
        
          }   
        
    
    }
   
    fclose (pFile);
    getch();
  
}

i get output
Bush
Mango
Dog
Cat

i m not getting 1st string in line ..
how to get this string??
i want each string individually ??how to get this??

try

while(getc(pFile)!='\n');   //but not ' '(space)

But if you want to store the strings in a 2d array:

//allocate space
2Darray=(char **)calloc(100,sizeof(char *));
for(i=0;i<100;i++) 2Darray[i]=(char *)calloc(100,sizeof(char ));
.............................................................................
//reading letter by letter
i=0;j=0;
while(!feof)
{
fread(2Darray[i][j++],sizeof(char),1,pFile);  // in case of error on this line,try using '&' in front of the '2Darray...'
if(2Darray[i][j-1]=='\n') {i+=1;j=0;}
}

Hope it works

This article has been dead for over six months. Start a new discussion instead.