Barjavel Barjavel - 1 year ago 76
C Question

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

The code I have is as follows:

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

The error message returned is:

Can't open file: No such file or directory

The file 'data.txt' definitely exists in the working directory (it exists in the directory that contains my .c and .h files), so why is fopen() is returning a NULL pointer?

Answer Source

Is it possible that the filename is not really "data.txt"?

On Unix, filenames are really byte strings not character strings, and it is possible to create files with controls such as backspace in their names. I have seen cases in the past in which copy-pasting into terminals resulted in files with ordinary-looking names, but trying to open the filename that appears in a directory listing results in an error.

One way to tell for sure that the filenames really are what you think they are:

$ python
>>> import os
>>> os.listdir('.')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download