Search code examples
cmacosdirectoryfopen

C - Can't create a file on the current directory in OSX


I have to save data in a file for a project (in C language). So i would like to use fopen to use fprintf to output my strings values on a file.

So, I do :

FILE * file;
file = fopen("./tmp.txt","w+");
outputData(); //my fonction to fprintf in the file
fclose(file);

But when i do that, this is not in the current directory but in my User directory of my compter (on OSX) and not on the current directory from where the app is lunch.

so, how can i change the current directory for my output file ? without hardCoding it ?

I'm executing my programme from: "/Users/Guillaume/OneDrive/Ephec/Os/Project1"

and the file tmp.txt is created in : "/Users/Guillaume" and i would like to create the file in the same directory as my project


Solution

  • I found a solution.

    char path[PATH_SIZE/2];
    strcpy(path,realpath(argv[0],0));
    

    I use the argv[0] part of my programme to get the path in conjonction with realpath()

    Man page : http://manpagesfr.free.fr/man/man3/realpath.3.html

    and store it in a pre-define string path