user3674062 user3674062 - 7 days ago 6
C Question

Unable to read from a file in C despite getting a success from fopen()

Thanks , this has been solved , please see updated code and output. Thanks Jonathan and everyone else.

I have written below code to read the file present in same directory.

#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
int main(){

FILE *fptr;


/*Tried putting different combinations like filename with
quotes|filename without quotes|complete path with quotes|complete path
without quotes*/

if((fptr=fopen("TestFile.txt","r"))==NULL){

printf("\nfopen() returning NULL: %d , %s \n",errno,strerror(errno));

}

int c;

while((c=fgetc(fptr))!=EOF){

printf("%c",c);

}}


And i am getting below output which is correct:


./a.out


DATA ENETERD AT RUN INSTANCE 1 ------> BLABLABLA

DATA ENETERD AT RUN INSTANCE 2 ------> YADAYADAYADA

DATA ENETERD AT RUN INSTANCE 3 ------> FOOBARFOOBAR

and my text file TestFile.txt was :

DATA ENETERD AT RUN INSTANCE 1 ------> BLABLABLA
DATA ENETERD AT RUN INSTANCE 2 ------> YADAYADAYADA
DATA ENETERD AT RUN INSTANCE 3 ------> FOOBARFOOBAR

Answer

To avoid the warning, you need to #include <string.h> in your code. Add an exit(1) in the error-handling if block :

if((fptr=fopen("TestFile.txt","r"))==NULL){
    printf("\nfopen() returning NULL: %d %s\n",errno, strerror(errno));
    exit(1);
}

The program needs to exit "gracefully" if the file doesn't exist. So, if there is no valid file present, the program will simply exit and not print anything on the stdout.

EDIT : Just adding on Jonathan's helpful comment on ignoring compiler's warnings :

"If you ignored a compiler warning — don't. If the compiler didn't warn you about the undeclared function strerror(), you need to find the options that make it report such problems (if you use gcc, you would use gcc -Wall -Wextra -Werror — and I'd add -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -Wold-style-declaration too, though clang doesn't like -Wold-style-declaration)."