Reputation: 49
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
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
Reputation: 117168
It's easy if you use std::string
s 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