I am a learning file handling in C. I tried implementing a program but no matter what I do the file pointer is still null.
I checked the spelling, the directory, even tried adding and removing .txt extension but I still don't get what is wrong with this program.
#include <stdio.h>
int main()
{
FILE *fptr1;
char filename[100], c;
printf("Enter the filename to open for reading: ");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
}
do {
c = fgetc(fptr1);
printf("%c", c);
} while (c != EOF);
fclose(fptr1);
return 0;
}
printf("Cannot open file %s \n", filename);toperror(filename);to get a hint of why it can't be opened.scanf("%s", filename);looks like the wrong tool since it will only read a word. If your filename contains whitespaces, it will be cut short. Usefgets(filename, sizeof filename, stdin)instead - and always check the return values from functions that can fail, likescanfandfgetscan.elseblock. Iffptr1 == NULLyou print out an error, but then go on and try to read the file anyway. What if you hardcode the file name rather than getting it from user input, same problem?