以一种标准的办法,获取工作目录

void GetWorkingFolder(std::string& folder){
    folder.resize(MAX_PATH*2 + 1, '\0'); //留长一点,防止后面再连接一个Cloudwalk时出错

    //获取当前程序目录,如果是C盘,则获取APPDATA目录,然后在末尾添加目录后缀
    HANDLE hExeHandle = GetModuleHandle(NULL);
    if(hExeHandle != nullptr) {
        GetModuleFileNameA((HMODULE)hExeHandle, &folder[0], MAX_PATH);
        folder = folder.substr(0, folder.find_last_of("\\") + 1);
    } else { //失败场景下,获取当前工作目录
        if (0 == GetCurrentDirectoryA(MAX_PATH, &folder[0])) {
            //再失败,那就只能默认.\目录了
            folder = ".";
        }
    }

    //判断是否首字母为C,写死吧,不去判断windows是否安装在其他盘了
    if ( (folder[0] == 'C') || (folder[0] == 'c') ) {
        std::string strTemp(MAX_PATH + 1, '\0');
        if (S_OK == SHGetFolderPathA(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_DEFAULT, &strTemp[0])) {
            folder = strTemp;
        }
    }

    //判断最后一个字符是否为
    if (folder[folder.length() - 1] != '\\') {
        folder += '\\';
    }
}
posted @ 2019-08-07 13:48  日月王  阅读(255)  评论(0编辑  收藏  举报