1
votes

I'm trying to use fopen("somefile", "r") to read a file (that exists) that is in the same directory as my C code (ex: main.c).

FILE *myFile = fopen("somefile", "r");
if(myFile == NULL){
  prinf("the pointer returns null");
}

I'm using macOS high sierra (I can't update to more recent versions of macOS because my computer is too old). When I run the code I get a null pointer.

I have another computer where I have installed Ubuntu. When I run the same code above I don't get a null pointer.

I'm using CLion 2020.3 as my IDE and I run the code through it.

Is there a way to fix this weird behavior on macOS. I've tried putting the absolute path but It still doesn't work.

I want to add that I'm sure of my file name and extension and I don't think the problem is related to that.

Using perror I get the following Error: : No such file or directory

My directory looks like this

myProject
  |____ src
         |____ CMakeLists.txt
         |____ main.c
         |____ main.h
         |____ somefile

I tired giving the full path of a file like

/Users/username/CLionProjets/myProject/src/somefile

but still didn't work.

EDIT* Now it works with the absolute path I forgot the c in CLionProjets.

EDIT** I'm curious to know why I need to put in the absolute path on macOS but not on Linux (Ubuntu) ?

2
perror gives em Error: : No such file or directory - BreezeWind
Check the default directory the code runs in. The executable is not necessarily started in the directory with your code. Or use a complete path. - Aganju
I used a complete path and it still doesn't work :/ - BreezeWind
i added the path to the question details - BreezeWind
That was dumb of me. I forgot the c. Now it works! Thx - BreezeWind

2 Answers

1
votes

that is in the same directory as my C code (ex: main.c).

How is the executable supposed to know, where your C code resides? Hint: It doesn't. If you specify a file path that's not absolute, it's taken relative to the current working directory. The current working directory is determined by from where and how you're launching the application.

In Linux try this:

cd /
/absolute/path/to/your/executable

same problem. For this to make it work you must change the working directory appropriately before launching the application.

0
votes

The directory for the source files, the executable file and the current directory of the running executable might be different locations.

Your Mac/OS IDE probably starts the program from a different directory than what you do on linux.

You can determine the current directory of the running program this way:

#include <stdio.h>
#include <unistd.h>

int main() {
    char buf[MAX_PATH];
    if (getcwd(buf, MAX_PATH)) {
        printf("no current directory for %s\n", argv[0]);
    } else {
        printf("current directory for %s: %s\n", argv[0], buf);
    }
    ...
}