Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 761
Barjavel Avatar asked Jul 13 '11 22:07

Barjavel


People also ask

Does fopen return NULL?

Probably fopen never returned NULL; you only assumed it did, based on faulty logic elsewhere in your code. First of all, put printf("Error: can't open the file! errno: %d\n", errno); in an else block. Secondly, do not use == to compare strings; use strcmp instead.

Does fopen return a pointer?

The fopen function returns a pointer to a FILE object associated with the named file. If the file cannot be opened, a NULL value is returned.

Why is file pointer NULL in C?

A null is used to indicate failure because no file pointer will ever have that value. If a file is opened foe writing, any pre-exiting file with that name will be overwritten. This is because when a file is opened in a write mode, a new file is created.

When fopen () is not able to open a file it returns?

Explanation: fopen() returns NULL if it is not able to open the given file due to any of the reasons like file not present, inappropriate permissions, etc.


2 Answers

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.

like image 156
Jacob Avatar answered Sep 21 '22 16:09

Jacob


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('.')
like image 23
wberry Avatar answered Sep 21 '22 16:09

wberry