I'm trying to write code that reads couple of numbers from FILE in the form of x y and stores them in two arrays, and i want the function to returns the number of couples, i tried with a FILE that contains 5 couples, but it seems that FILE *ptr goes beyond and reaches the sixth lines, here is my code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int X[100],Y[100];
int i=0; int Ncouple = 0 ;int M = 5;
FILE *fptr;
fptr = fopen("num.data", "r");
if( fptr == NULL)
{
printf("fail");
exit(1);
}
while(!feof(fptr))
{
fscanf(fptr,"%d %d",&X[i],&Y[i]);
printf("\nX[%d] = %d Y[%d] = %d\n",i,X[i],i,Y[i]);
i++;Ncouple++;
}
fclose(fptr);
return 0;
}
When i execute i get X[6] and Y[6] but my date file contains only 5 lines. Where am i wrong ?
The condition in the while statement is the reason of the behavior that you described.
This condition will be equal to true after you will try already to read a non-existent record in the file.
Rewrite the while loop like
Pay attention to that instead of this line of declarations
it would be better to write
Or at least like