Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

c - fopen() returns a NULL pointer while the file exists on macOS but not on linux, why and how to fix this?

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) ?

question from:https://stackoverflow.com/questions/65863024/fopen-returns-a-null-pointer-while-the-file-exists-on-macos-but-not-on-linux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...