简体   繁体   中英

How to stop a C file reading before EOF?

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?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM