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?
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.
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.
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.
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.
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.
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('.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With