I have a file input.txt which has data like
0 0 0 0 0 0 1
0 0 0 6 0 9 0
0 0 1 0 1 1 0
1 0 0 0 0 4 0
0 0 3 0 1 5 6
I need to read this file and store it in a 2D array.
Plz tell me .. how to do that..
2D means 1 for rows , 1 for columns I guess .
If this is so, try the above code, it works also with lines of different lengths like:
0 0 0 0 0 1 1
0 0 0 6 0 9 0 5 4
0 0 1 0 1 1 0 6 6 6
1 0 0 0 0 4 0
0 0 3 0 1 5 6
//---------------------------------------------- C code:
#include <stdlib.h>
#include <stdio.h>
#define M 1000
#define N 500
main ()
{
FILE * fp;
int my_array[M][N];
int i,k,a,maxc;
i=0;
k=0;
maxc=0;
fp = fopen("/input.txt", "rb");
do{
a = fgetc(fp);
my_array[i][k] = a;
i++;
if(a==13){my_array[i][k]='\0';
if(i>maxc)maxc=i;
i=0;
k++;
}
} while((a!=EOF)& (i<M)&(k<N));
fclose(fp);
system("pause");
/*view stored data*/
int j,m;
for(m=0;m<k;m++){
for(j=0; j<maxc;j++) {if(my_array[j][m]!='\0')printf ("%c",my_array[j][m]);}
printf("\n");
}
system("pause");
}
//-----------------------------------------------------------------
Why a==13? this is the ASCII for newline , u can use it to determine where to start a new array row.
Bye!