0

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

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
Guillaume Lemer
  • 63
  • 1
  • 3
  • 10
  • Please show more information. Show how you run your program and show what the current directory of your terminal is when you run the program (use the shell command `pwd`). – Jabberwocky Nov 07 '19 at 10:30
  • 2
    I don't understand what you want to do exactly. If you want to get location to your home dir, use `getenv("HOME")`. To get location to your current directory, use `getenv("PWD")` – Mihir Luthra Nov 07 '19 at 10:34
  • sorry for the long time between my modifications i was at my lectures – Guillaume Lemer Nov 07 '19 at 16:02
  • 1
    You seem to confuse the current directory (aka the working directory) and the directory where the executable resides. For the later, see [this question](https://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe). – AProgrammer Nov 07 '19 at 16:06

2 Answers2

0

You can try using full path, as on linux:

FILE * file;
file = fopen("/home/toto/tmp.txt","w+");

You can also check file access using access

Hugo Martin
  • 167
  • 6
0

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

Guillaume Lemer
  • 63
  • 1
  • 3
  • 10