将wchar_t *转换为char *时出现问题 [英] Issue in Converting wchar_t* to char*

查看:432
本文介绍了将wchar_t *转换为char *时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Windows 7中读取当前目录,该目录的语言环境与当前使用的语言环境不同。所以我考虑使用GetCurrentDirectoryW(),因为它与wchar_t *是Unicode兼容的。但是,我需要使用现有的API,因此需要将其转换为char *。为此,我使用了wcstombs()函数。但是,转换未正确进行。以下是我使用的代码:

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);

我当前所在的目录是C:\特斯塔敌人。转换完成后,只有完整路径的 C:\部分才能正确转换为char *。其他字符不是,它们是垃圾值。我使用的这种方法有什么问题?我该如何纠正?

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?

谢谢!

推荐答案

问题是没有适当的转换可能。宽字符可能没有等价的常规字符(这就是为什么 wchar 首先存在的原因。因此,您应该使用 wprintf

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);

这篇关于将wchar_t *转换为char *时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆