1

I'm writing an application for windows, and I need to find the location of the appdata folder, to save, well, appdata to it. I'm using C++. When I did some research on this, I found some answers like, for example "getenv("APPDATA")". I could use that but that question was answered in like 2012 so there might be better ways to do it now in 2021. Thanks for the help!

#include <iostream>

int main() {
    std::string appdataLocation;
    //TODO: Find appdata folder location.
    //enter code here
    std::cout << appdataLocation << '\n';
}

Some people have been suggesting that this is a duplicate question. That question was asked 10 years ago. There may be better ways to do it right now, which is why I'm asking.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
avighnac
  • 376
  • 4
  • 12

2 Answers2

0

There IS (and always has been) a way to fetch this using the API:

CoInitialize(0);
wchar_t AppDataFolder[MAX_PATH];
SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, AppDataFolder);

but there are few reasons to do so for APPDATA, since the environment variable is available.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

you can use Windows API alternatively:

    TCHAR appdata[MAX_PATH] = {0};
    SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, appdata);

https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderpatha

xinsheng
  • 96
  • 8
  • Strange. I tried using this but running the program didn't print anything. ```cpp #include #include int main() { std::string appdata; TCHAR appdata[MAX_PATH] = {0}; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, appdata); std::cout << appdata << '\n'; } ``` – avighnac Nov 12 '21 at 07:14
  • Okay, now when I try to compile it, it tells me that 'SHGetFolderPath was not declared in this scope.' EDIT: Nevermind, I managed to fix it, it works. Thanks! – avighnac Nov 12 '21 at 07:16