2

Is there a way to set the output directory of a file in the same one where the executable is located and not where the executable is executed?

      ofstream outputFile;
      outputFile.open("text.txt");
      outputFile<<"test";

When I click on the .exe it typically outputs the file in the same directory I started it but when I execute it in different ways say for example with a .BAT file, the output directory is automatically set where I started the .BAT file (not where the .exe is located)

TuskAct4
  • 83
  • 1
  • 1
  • 5
  • 3
    Code shouldn't assume it has write access to the application directory, since generally it's not allowed. Is there another problem that you trying to solve with this? – Eryk Sun Apr 23 '20 at 21:19
  • `outputFile.open("C:\\My Project\\Output Where Exe Is Located\\text.txt");` – Eljay Apr 23 '20 at 21:21
  • A quick-and-dirty solution for Windows: use `argv[0]` – rustyx Apr 23 '20 at 21:23
  • Thank you all for the answers! I'm just getting started with C++ and I don't seem to understand what I have to do after getting where the program directory is running from. Do I have do use Setcurrentdirectory()? – TuskAct4 Apr 23 '20 at 21:30
  • 1
    @rustyx, the executable path is often either searched for beforehand and passed directly to `CreateProcessW` as `lpApplicationName` (e.g. cmd.exe does this) or the system searches for it via the first white-space delimited argument of `lpCommandLine`. So `argv[0]` is not necessarily a qualified path, and no code should use it as such. The application directory can be determined reliably via `GetModuleFileNameW`, or via `GetEnvironmentVariableW` with the dynamic variable "\_\_APPDIR\_\_". – Eryk Sun Apr 23 '20 at 22:03

0 Answers0