I'am trying to read a data from a textfile with fscanf but after readData function program is crashing. It's not entering the loop statement. In the console there is just printing data is read. When i tried to reading data in main it's working but i need to read in function.
#include <stdio.h>
#include <stdio.h>
void readData(int array[10][3]);
int main(void)
{
int data[10][3],i;
readData(data);
for(i=0; i<10; i )
{
printf("%d %d %d \n",data[i][0],data[i][1],data[i][2]);
}
}
void readData(array[10][3])
{
int i;
FILE *ptr = fopen("phonedata.txt","r");
if(ptr == NULL)
{
printf("There is no file");
}
else
{
printf("Data is read");
}
while(fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) != EOF);
{
i ;
}
}
CodePudding user response:
For starters you forgot to specify the type of the parameter in the function definition
void readData(array[10][3])
you need to write
void readData(int array[10][3])
Within the function you are using the uninitialized variable i
.
int i;
You have to write
int i = 0;
You have also to remove the semicolon after the while loop
while(fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) != EOF);
And it is better to write the condition like
while( i < 10 && fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) == 3)
And you need to place the while loop in the else statement
else
{
printf("Data is read");
while( i < 10 && fscanf(ptr, "%d %d %d",&array[i][0],&array[i][1],array[i][2]) == 3)
{
i ;
}
}
And you should return from the function the number of "rows" filled.
And before exiting the function the file must be closed.
fclose( ptr );