fopen() returning a NULL pointer, but the file definitely exists

前端 未结 7 771
不思量自难忘°
不思量自难忘° 2020-12-31 02:25

The code I have is as follows:

FILE *txt_file = fopen(\"data.txt\", \"r\");
if (txt_file == NULL) {
    perror(\"Can\'t open file\");
} 

Th

相关标签:
7条回答
  • 2020-12-31 02:54

    I encountered the same errno to fopen on Linux from a script file corrupted by Windows.

    ENOENT 2 No such file or directory

    Wordpad on Windows (or some other Microsoft culprit) inserted CRLF = (0x0D, 0x0A) into my linux script files in place of newline = LF = 0x0A. When I read the file name into a buffer and called fopen if failed due to the invisible appended CR character.

    In the Codelite editor on Linux Mint I was able to show EOL characters (View > Display EOL) and remove them with find and replace, using copy and paste of the CRLF from the corrupted script files and the LF from an uncorrupted file into the text fields.

    0 讨论(0)
  • 2020-12-31 02:55

    I just had a similar issue like this where I knew the path was correct and the file was in the right location. Check the file permissions. It is possible that the program cannot access the file because it is getting permission denied.

    0 讨论(0)
  • 2020-12-31 03:01

    My problem was that I had a file filename.txt and I didn't realize that in reality it was filename.txt.txt due to windows not showing the extension.

    0 讨论(0)
  • 2020-12-31 03:02

    Make sure that your input file is in the same directory as the executable, which may be different than the one where your source files are kept. If you're running the program in an IDE debugger, make sure that your working directory is set to the location of the input file. Also, if you're running in *nix rather than Windows, you may need to prepend a "./" to the input filename.

    0 讨论(0)
  • 2020-12-31 03:02

    Invisible SPACE character in file name?

    Once a year I have a similar problem: I try to open a file with the filename in a string, obtained from a sting operation. When I print the name it seems OK, but fopen() returns a null pointer. The only help is printing the name with delimiters showing the exact beginning and end of the filename string. Of course this does not not help with unprintable chars.

    0 讨论(0)
  • 2020-12-31 03:13

    Standard problem. Try

    FILE *txt_file = fopen("C:\\SomeFolder\\data.txt", "r");
    

    I.e. try opening it with the full absolute path first ; if it works then you just have to figure out what the current directory is with _getcwd() and then fix your relative path.

    0 讨论(0)
提交回复
热议问题