Read integer array from File in C

this require 2 files:
1) f.txt : which our array is stored
Data:
1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9

2) Programe file : where code resides
Code:
#include<stdio.h>
void main()
{
FILE *f; 
int R=0,C=0,No_OF_COLUMN=0; //Store Row and Column pointer
int i=0,j=0; //Temperory variable
int ARR[100][100]; //Final array where values to be stored
char ch,c[10];

f=fopen("f.txt","r");
while((ch=(char)fgetc(f))!=EOF)
{
if(ch==' ' )
{
c[i]='\0';
ARR[R][C]=atoi(c); // store value into array
i=0;
C++;//Increament Column pointer
if(No_OF_COLUMN<C)
{
No_OF_COLUMN=C;
}
}
else if(ch == '\n')
{
c[i]='\0';
ARR[R][C]=atoi(c); // store value into array
i=0;
C=0; //reset Column pointer
R++; //increament Row pointer
}
else
{
c[i]=ch;
i++;
//printf("%c",ch);
}
}
fclose(f);
for(i=0;i<R;i++)
{
for(j=0;j<No_OF_COLUMN;j++)
{
printf(" %d ",ARR[i][j]);
}
printf("\n");
}
}

Output:

1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9
1 2 3 4 5 6 7 7 8 9

0 comments:

Post a Comment