问题
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