std::string转wchar_t,WCHAR_windowsAPI

std::string转wchar_t,WCHAR

#include <string>
#include <windows.h>

std::string str = "Your ASCII or UTF-8 string";
int wstr_size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
std::vector<wchar_t> wstr(wstr_size);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &wstr[0], wstr_size);

// 如果需要将结果转换为 std::wstring
std::wstring wstr_result(&wstr[0], wstr_size - 1);

 或者:

目录不存在则创建

std::string CFileOperation::GetCurrentPath()
{
    TCHAR  path[MAX_PATH];
    //string *aa;
    GetModuleFileName(NULL, path, MAX_PATH);
    std::cout << "Current file path: " << path << std::endl;
    std::string str = TCHARToStdString(path);
    return str;
}

 

 LPCWSTR dir_path = L"example_directory";
        string current_path = GetCurrentPath();
        std::string find_str = ".exe";
        size_t find_index = current_path.find(find_str);
        current_path = current_path.replace(find_index, find_str.length(), "_Log");
        
       
        std::wstring stemp = s2ws(current_path);

        LPCWSTR result = stemp.c_str();
        dir_path = result;

        // 检查目录是否存在
        DWORD dwAttrib = GetFileAttributesW(dir_path);

        if (dwAttrib == INVALID_FILE_ATTRIBUTES)
        {
            // 目录不存在,尝试创建它
            if (CreateDirectoryW(dir_path, NULL)) {
                std::wcout << L"Directory created: " << dir_path << std::endl;
            }
            else {
                // 获取错误信息
                DWORD err = GetLastError();
                std::wcerr << L"Failed to create directory: " << dir_path << L" Error: " << err << std::endl;
                return 1;
            }
        }

 

 LPCWSTR dir_path = L"example_directory";        string current_path = GetCurrentPath();        std::string find_str = ".exe";        size_t find_index = current_path.find(find_str);        current_path = current_path.replace(find_index, find_str.length(), "_Log");                       std::wstring stemp = s2ws(current_path);
        LPCWSTR result = stemp.c_str();        dir_path = result;
        // 检查目录是否存在        DWORD dwAttrib = GetFileAttributesW(dir_path);
        if (dwAttrib == INVALID_FILE_ATTRIBUTES)        {            // 目录不存在,尝试创建它            if (CreateDirectoryW(dir_path, NULL)) {                std::wcout << L"Directory created: " << dir_path << std::endl;            }            else {                // 获取错误信息                DWORD err = GetLastError();                std::wcerr << L"Failed to create directory: " << dir_path << L" Error: " << err << std::endl;                return 1;            }        }
posted @ 2025-01-07 11:06  txwtech  阅读(109)  评论(0)    收藏  举报