C++ Проверка запуска программы из определённой папки

r3xq1

Проверенный
Проверенный
r3xq1

r3xq1

Проверенный
Проверенный
Сообщения
53
Реакции
29
В кодировке Много-байтовой:
C++:
#include <iostream>
#include <windows.h>
#include <string>

/* путь возвращения ...\Debug\TestThread.exe */
std::string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileName(NULL, buffer, MAX_PATH);
    std::string::size_type pos = std::string(buffer).find_last_of("\\/");
    return std::string(buffer).substr(0, pos);
}
// http://www.cplusplus.com/reference/cstdlib/getenv/
std::string getEnvVar(std::string const& key)
{
    char const* val = getenv(key.c_str());
    return val == NULL ? std::string() : std::string(val);
}


int main() {
    // Проверяем путь
    if (getEnvVar("APPDATA")._Starts_with(ExePath()) == 0)
    {
        // Если запущена не из папки AppData
        std::cout << "Filepath: " << getEnvVar("APPDATA") << std::endl; // Выводим полный путь до папки APPDATA
        system("pause"); // Пауза для консоли
    }
    else
    {
        // Если запущена из папки AppData
        std::cout << "So wtf: " << std::endl; // Выводим сообщение
        system("pause"); // Пауза для консоли
    }
    return 0;
}
В кодировке Unicode:
C++:
#include <iostream>
#include <windows.h>
#include <string>

/* ...\Debug\TestThread.exe */
std::string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileNameA(NULL, buffer, MAX_PATH);
    std::string::size_type pos = std::string(buffer).find_last_of("\\/");
    return std::string(buffer).substr(0, pos);
}

std::string getEnvVar(std::string const& key)
{
    char const* val = getenv(key.c_str());
    return val == NULL ? std::string() : std::string(val);
}


int main() {
    if (getEnvVar("APPDATA")._Starts_with(ExePath()) == 0)
    {
        // Если запущена не из папки AppData
        std::cout << "Filepath: " << getEnvVar("APPDATA") << std::endl;
        system("pause");
    }
    else
    {
        // Если запущена из папки AppData
        std::cout << "So wtf: " << std::endl;
        system("pause");
    }
    return 0;
}
 

Сверху Снизу