2

I'm just new at coding and stuck on using AppData path in c++ cmd code. How can I correctly use AppData in the code below?

 #include <stdlib.h>
 #include <stdio.h>
 #include <iostream>

int main(int argc, char** argv){
    char* appdata = getenv("APPDATA");
    printf("Appdata: %s\n",appdata);
    system("schtasks /create /tn System64 /tr   (need to use appdata path here)\\Honeygain\\Honeygain.exe /sc ONLOGON");
    return 0;

    
}
Onur Kaya
  • 29
  • 8

2 Answers2

4

It's easy if you use std::strings to concatenate the different parts.

#include <cstdlib>
#include <iostream>
#include <string>

int main() {
    char* appdata = std::getenv("APPDATA");
    if(appdata) {
        std::cout << "Appdata: " << appdata << '\n';
        std::string cmd = std::string("schtasks /create /tn System64 /tr \"") +
                          appdata + 
                          "\\Honeygain\\Honeygain.exe\" /sc ONLOGON";
        system(cmd.c_str());
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • If anyone else is wondering, why `std::getenv()` does not return a `const char*`: It's [because of backwards compatibility](https://stackoverflow.com/questions/36827942/why-does-getenv-return-a-non-const-string) apparently. I recommend storing it as `const char*`, though, because modifying the data is *undefined behavior*. – Neonit Aug 04 '23 at 06:16
  • @Neonit `getenv` is older than `const` when it comes to C if I'm not mistaken and C _still_ allows non-`const` `char*` at string literals - even though mutating them has UB. – Ted Lyngmo Aug 04 '23 at 07:10
3

Teds answer is correct. I just want to add that for C++17 and beyond, using std::filesystem::path is the preferred way to handle paths:

    char* appdata = std::getenv("APPDATA");
    if(appdata) {
        std::filesystem::path executablePath(appdata);
        executablePath /= "Honeygain\\Honeygain.exe";
        std::cout << "Appdata: " << appdata << '\n';
        std::string cmd = std::string("schtasks /create /tn System64 /tr \"")
                          + executablePath.string()
                          + "\" /sc ONLOGON";
        system(cmd.c_str());
    }
Wutz
  • 2,246
  • 13
  • 15
  • 1
    I would even make it `auto executablePath = std::filesystem::path{appdata} / "Honeygain" / "Honeygain.exe";` – Ted Lyngmo Sep 27 '20 at 14:52