0

I have a CLI app and I want it to be able to be called in any directory (e.g. C:\Users\Me> CLI_App.exe {args} or some\other\path> CLI_App.exe {args}) but I want the files to be saved into the same place of the exe instead of the directory of where the app is called. I would prefer the solution to be cross platform.

I have tried doing cout<<argv[0];
(to see if it outputs the path of the file so that I could make a file path of argv[0] + "exaample.txt")
but all I get as the output is just CLI_App.exe or sometimes true

Replying to yunnosch, I want the files to stay in the same place. This means that if I use the app with the terminal from a different folder, I'd like it to open the exact file that the user put in. I don't want the app to get confused, thinking the file doesn't exist in the current folder and then creating a new one. Even if a file with the same name exists in another folder, I want the app to recognize and use the correct one.

1cubealot
  • 5
  • 2
  • Windows have some specific functions to [get the *module handle*](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea) to the executable, and from that you can get its directory. I don't remember all the functions, but some quick Internet searching, and sifting through the documentation, should help. – Some programmer dude Aug 26 '23 at 07:00
  • For getting the path of the exe see here: https://stackoverflow.com/questions/2647429/c-windows-path-to-the-folder-where-the-executable-is-located, and here: https://stackoverflow.com/questions/1528298/get-path-of-executable. – wohlstad Aug 26 '23 at 07:09
  • 1
    It is OK that you decide to write files where your executable is, your choice. You might however want to explain your reasons for it, so that it becomes possible to write answers based on what you indirectly/actually want to achieve and help with that instead of with what you decided will get you there. Compare https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Yunnosch Aug 26 '23 at 07:57
  • You may also try std::filesystem::current_path . – moriaz Aug 26 '23 at 10:27
  • The more appropriate place for your use case might be `%APPDATA%`. Always assume that the app dir may be non-writable. – Osyotr Aug 26 '23 at 11:45
  • @moriaz That will return the working directory path, which is seldom the same path as where the executable program is located. – Some programmer dude Aug 26 '23 at 12:19
  • @Osyotr How would I write there and Is there a linux variant of that – 1cubealot Aug 26 '23 at 12:45
  • On windows, refer to `SHGetKnownFolderPath`. On linux, see https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html. For cross-platform solution consider something like this https://github.com/sago007/PlatformFolders – Osyotr Aug 26 '23 at 12:58

0 Answers0