c++ - Problems with fopen function on Mac -


i'm making simple application on mac (osx mavericks, compiling clang). problem when try open file using relative path, doesn't work. works if use absolute path.

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

it returns null.

it works if use: fp = fopen(" user/username/project_folder/file.txt", "r"); (project folder folder i'm compiling in, , has file.txt)

the file in same directory.

how can solve this?

also same code has worked time ago, , , other code uses fopen show same problem.

when run fopen without full path, uses current working directory of location ran program from. if working directory (obtained typing pwd in shell) where execute program from ~/my_folder/ , file.txt happens in ~/my_folder/bin/ if executable inside ~/my_folder/bin/ won't find file.txt. because looking ~/my_folder/file.txt.

so if running program different directory of file.txt either have provide absolute path or provide path relative directory running program from.

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

update

one workaround can used if have access string array argument (argv[]) of main method. first element of argv contain path (from working directory) used execute program. following simple program simple prints argument.

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

this print relative path including executable name. can replace executable name file.txt if file in same location executable. way load in both scenarios: when run double-clicking , when run command line navigating location of executable.

you may have take account possible ./ @ beginning of argv[0]. hope helps :)


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -