[英]C++ getting the path of APPDATA
I'm just new at coding and stuck on using AppData path in c++ cmd code.我只是编码新手,并坚持在 c++ cmd 代码中使用 AppData 路径。 How can I correctly use AppData in the code below?如何在下面的代码中正确使用 AppData?
#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;
}
It's easy if you use std::string
s to concatenate the different parts.如果您使用std::string
连接不同的部分,这很容易。
#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());
}
}
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:我只想为 C++17 及更高版本添加它,使用std::filesystem::path
是处理路径的首选方式:
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.