Reputation: 1316
I have a file which is a series of numbers that I am reading through C and then storing in an array. There is a new line at the end of the list which the pointer reads and sends to my array, which is problematic.
List of numbers:
9
8
6
5
23
42
Code:
FILE* fichier=NULL;
fichier = fopen("resultat.txt","r");
int i=0;
int ID[50];
while(fgetc(fichier)!=EOF && i<50){
fscanf(fichier,"%d",&ID[i]);
printf("%d\n",ID[i]);
i++;
}
fclose(fichier);
Output I have:
42
23
9
8
5
6
5
17081006
Output I want:
42
23
9
8
5
6
5
How can I stop it reading the last (empty except for a return) line?
Upvotes: 1
Views: 1079
Reputation: 11418
The problem lays on the behaviour of feof()
and the way you are using it. feof()
works by returning whether the last read operation on a file read the EOF mark or actual data (well, you are using fgetc()
but the behaviour is the same anyway)
Your read loop doesn't do a read before asking for EOF
. Instead, you are first asking if EOF
is found, and if not, do a read operation, print the result and back again. After the last number read, fgetc()
still returns not EOF
, so the loop enters again and you read.... nothing, so printf()
prints nothing intelligible. Now it is when you have reached EOF
, and the next time you ask it, fgetc()
returns EOF
.
Try changing your code as follows. I use feof()
instead of fgetc()
so I don't do an extra read to see if I have reached EOF
.
FILE* fichier=NULL;
int i=0;
int ID[50];
int num; /* temporary storage for number read from file */
fichier = fopen("resultat.txt","r");
fscanf(fichier,"%d",&num); /* first read, outside read loop */
while(!feof(fichier) && i<50) /* now you can ask for EOF */
{
ID[i] = num; /* if not EOF, store data read */
printf("%d\n",ID[i]); /* and print it */
fscanf(fichier,"%d",&num); /* then, read some more */
i++;
}
fclose(fichier);
Upvotes: 1
Reputation: 75062
You should stop printing when fscanf()
fails to read one data.
Also return value of fopen()
should be checked in order to avoid passing NULL
to file manipulating functions and invoking undefined behavior.
FILE* fichier=NULL;
fichier = fopen("resultat.txt","r");
int i=0;
int ID[50];
if (fichier != NULL) {
while(i<50 && fscanf(fichier,"%d",&ID[i]) == 1){
printf("%d\n",ID[i]);
i++;
}
fclose(fichier);
}
Upvotes: 4