Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with fopen function on Mac

Tags:

c++

c

macos

fopen

I'm making a simple application on Mac (OSX Mavericks, compiling with clang). The problem is that when I try to open a file using the relative path, it doesn't work. It works if I use the absolute path.

For example, if I try : fp = fopen("file.txt", "r");

It returns NULL.

It only works if I use: fp = fopen(" User/UserName/Project_folder/file.txt", "r"); (project folder is the folder that I'm compiling in, and it has my file.txt)

The file is in the exactly same directory.

How I can solve this?

Also the same code has worked well some time ago, and now this and other code that uses the fopen show the same problem.

like image 856
Breno Rodrigues Avatar asked Sep 13 '25 11:09

Breno Rodrigues


2 Answers

When you run fopen without full path, it uses the current working directory of the location where you ran the program from. So if your working directory (obtained by typing pwd in shell) where you execute your program from is ~/my_folder/ and file.txt happens to be in ~/my_folder/bin/ then even if your executable is inside ~/my_folder/bin/ it won't find file.txt. Because it will be looking for ~/my_folder/file.txt.

So if you are running your program from a different directory than that of file.txt then you either have to provide absolute path or provide a path relative to the directory that you are running your program from.

For info on working directory see http://www.linfo.org/current_directory.html

Update

One workaround that can be used if you have access to the string array argument (argv[]) of main method. The first element of argv will contain the path (from working directory) that was used to execute your program. Following simple program simple prints that argument.

int main(int argc, char *argv[])
{
  printf("Path relative to the working directory is: %s\n", argv[0]);
  return 0;
}

This will print the relative path including the executable name. You can replace executable name with file.txt if that file is in the same location as executable. This way it will load in both scenarios: when run by double-clicking and also when run from command line by navigating to the location of the executable.

You may also have to take into account the possible ./ at the beginning of argv[0]. Hope it helps :)

like image 197
bytefire Avatar answered Sep 15 '25 00:09

bytefire


I'm not exactly sure, but I think that on macs the default directory in which the program searches for relative paths is not the current directory but the user directory. Try to put file.txt in this one.

(Note: I remember having a problem like this once, but I am not sure it was with fopen. Well, can't hurt to try...)

like image 31
Eternal Avatar answered Sep 15 '25 02:09

Eternal