Joshua King
Joshua King

Reputation: 49

C++ getting the path of APPDATA

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;

    
}

Upvotes: 2

Views: 2145

Answers (2)

Wutz
Wutz

Reputation: 2942

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());
    }

Upvotes: 3

Ted Lyngmo
Ted Lyngmo

Reputation: 117168

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());
    }
}

Upvotes: 4

Related Questions