簡體   English   中英

C++獲取APPDATA的路徑

[英]C++ getting the path of APPDATA

我只是編碼新手,並堅持在 c++ cmd 代碼中使用 AppData 路徑。 如何在下面的代碼中正確使用 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;

    
}

如果您使用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());
    }
}

泰德的回答是正確的。 我只想為 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM