dense8
dense8

Reputation: 718

fscanf returns -1, fgets returns 0 but fopen is working, what is the problem?

I am trying to read line by line and put the values on an integer that I will use later on. I used fgets and it returned 0 and did not go into the while loop, now I am using fscanf and it returns -1 and I can't get into the while loop too. I will insert the code segment and the text files I use here.

    FILE *f;
    f = fopen( fileNames[i], "r");
    if (f == NULL) {
        printf("Failed to open a file\n");
    }
                
    int number;

    printf("fscanf value %d\n", (fscanf( f, "%d", &number))); //returns -1 always
    while( fscanf( f, "%d", &number) > 0){ // does NOT get into the while loop
        for(int i = 0; i < intervalCount; i++){
            if( // operations I use in my project ){
                // operations that I will use in my project
            }
        }
    }
    fclose(f);

text files are something like

1534
1535
1420
1400
1600
1601
2500
1536
1537
1538

please help, I seriously don't understand what is the problem.

For some clarification - f is not NULL, it does not go into the if statement.

Upvotes: 0

Views: 53

Answers (1)

chqrlie
chqrlie

Reputation: 144818

You should exit from the function if fopen() fails, otherwise you have undefined behavior when calling fscanf() with a null pointer.

More generally, you should output more information in diagnostic messages to help find why these calls fail.

Single stepping in a debugger is a good approach too.

#include <errno.h>
#include <stdio.h>
#include <string.h>

[...]

    FILE *f;
    f = fopen(fileNames[i], "r");
    if (f == NULL) {
        fprintf(stderr, "Failed to open file %s: %s\n",
                fileNames[i], strerror(errno));
    } else {
        int number;
        int res = fscanf(f, "%d", &number);
        if (res != 1) {
            fprintf(stderr, "reading from %s: fscanf returns %d\n",
                    fileNames[i], res);
        } else {
            while (fscanf(f, "%d", &number) == 1) {
                for (int i = 0; i < intervalCount; i++) {
                    if (// operations I use in my project) {
                        // operations that I will use in my project
                    }
                }
            }
        }
        fclose(f);
    }

Upvotes: 1

Related Questions