简体   繁体   中英

C language: reading a .txt file


I'm trying to write a program that reads a text file, using C with Visual Studio.
This is my current code (which doesn't work):

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *filePTR;
    char fileRow[100];

    filePTR = fopen_s(&filePTR, "text.txt", "r");

    // Opens the file
    if(filePTR){
        while(!feof(filePTR)) {
            // Reads file row
            fgets(fileRow, 100, filePTR);
            // Displays file row
            printf("%s \n", fileRow);
        }
        printf("\nEnd of file.");
    }
    else {
        printf("ERROR! Impossible to read the file.");
    }

    // Closes the file
    fclose(filePTR);

    return 0;
}

I'm getting the following warning:

'filePTR' may be '0': this condition does not meet the function specification 'fclose'.

What am I doing wrong? I haven't been programming in C since a while ...

The problems begin long before the fclose . This line is incorrect:

filePTR = fopen_s(&filePTR, "text.txt", "r");

It overwites the file pointer already assigned by passing a pointer as the function argument &filePTR.

The function returns an error status, not the file pointer. Please see the man page :

Return Value Zero if successful; an error code on failure.

Also, please see Why is while ( !feof (file) ) always wrong?

I suggest this:

#include <stdio.h>
#include <stdlib.h>

int main(void) {                        // correct definition
    FILE *filePTR;
    char fileRow[100];

    if(fopen_s(&filePTR, "text.txt", "r") == 0) {
        while(fgets(fileRow, sizeof fileRow, filePTR) != NULL) {
            printf("%s", fileRow);      // the string already contains a newline
        }
        fclose(filePTR);                // only close if it was opened
        printf("\nEnd of file.");
    }
    else {
        printf("ERROR! Impossible to read the file.");
    }

    return 0;
}

Note that I moved the fclose call up. You can't close a file that you did not open.

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