File pointer null in c

119 Views Asked by At

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

There are 1 best solutions below

2
Abdelhak Mez On

I tried your code it works fine , you just have to add (filename.txt) as your input like (myfile.txt)

well i changed some in your code to make it more simpler ,so here is the changed sections

First from this

 if (fptr1 == NULL)
    {
        printf("Cannot open file %s \n", filename);
    }

to this

 if (fptr1 == NULL)
        printf("Cannot open file %s \n", filename);

Because when you have only one line that execute after the condition is true , you can get ride of the { }

also i changed the ( do while ) to ( while ) Second from this

 do {
        c = fgetc(fptr1);
        printf("%c", c);
    } while (c != EOF);

to this

    while(!feof(fptr1)){
        c = fgetc(fptr1);
        printf("%c",c);
    }

Here the line feof is a function that means the end of file

We are checking if its NOT the end of file ( !feof ) , if thats true then we can read from the file and print the result . the loop ends when c = EOF .

and thats it.

NOTE : your file name should be without spaces ( myfile.txt ) and not (my file.txt) because we are using scanf() function , it stoppes when countering a space ( blank space ) , so keep that in mind.