Search code examples
cfilefopen

c++ fopen() returning a NULL pointer when I try using a char array or pointer


I'm attempting to open a file with fopen and storing it into a FILE*.

The code I have is as follows:


    char path[300];
printf("File name: ");
fgets(path, 300, stdin); FILE* fp;
fp = fopen(path, "r");
if (fp == NULL) {
printf("file does not exist\n");
}

When I run the above code, I get a file not found error; however, when I hardcode the file name:


    fp = fopen("test.txt", "r");

The code works as intended. I think the issue might have something to do with the data type since fopen requires a const char* for it's parameter. I've tried using char*'s but to no avail.


Solution

  • No, it's much simpler than that. When you use fgets the newline character at the end of the line gets included in the char array. That newline is then messing up your attempt to open the file.

    Incidentally fopen does not require a const char* parameter. It requires a parameter which can be converted to a const char*. That includes char* as well as char [].