Issue in Converting wchar_t* to char*

孤街浪徒 提交于 2019-12-13 04:47:48

问题


I need to read the current directory in Windows 7 which is in a different locale than the one that is currently used. So I thought of using GetCurrentDirectoryW() since it is unicode compatible, with wchar_t*. However, I need to use an existing API, so I need to convert this to char*. For this purpose I used the wcstombs() function. However, the conversion is not happening properly. Included below is the code that I used:

    wchar_t w_currentDir[MAX_PATH + 100];
    char currentDir[MAX_PATH + 100];
    GetCurrentDirectoryW(MAX_PATH, w_currentDir);
    wcstombs (currentDir, w_currentDir, MAX_PATH + 100);
    printf("%s \n", currentDir);

The current directory that I'm in is C:\特斯塔敌人. When the conversion is done, Only the 'C:\' part of the full path is converted to char* properly. The other characters are not, they are junk values. What is the problem in this approach that I'm using? How can I rectify this?

Thank you!


回答1:


The problem is that there is no appropriate conversion possible. A wide character may not have a regular char equivalent (which is why wchar exists in the first place. So you should be using wprintf:

GetCurrentDirectoryW(MAX_PATH, w_currentDir);
wprintf("%s \n", w_currentDir);


来源:https://stackoverflow.com/questions/13447756/issue-in-converting-wchar-t-to-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!