Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why program crashes after fscanf

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading