2016-11-22 104 views
1

嘿。C - wchar_t打印不需要的字符

我想列出具有非英文字符文件的文件夹。 下面的函数接受一个参数,比如C:\并列出里面的文件。但不是100%正确。对于土耳其字符,它会打印一些符号,即使我使用了wchar_t类型。

void listFolder(const wchar_t* path){ 
DIR *dir; 
struct _wdirent *dp; 
wchar_t * file_name; 
wchar_t fullpath[MAX_PATH]; 
dir = _wopendir(path); 

while ((dp=_wreaddir(dir)) != NULL) { 
    //printf("[i]debug: \t%s\n", dp->d_name); 
    if (!wcscmp(dp->d_name, L".") || !wcscmp(dp->d_name, L"..")){ 
     // do nothing 
    } 
    else { 
     file_name = dp->d_name; // use it 
     wprintf(L"[*]file_name: \t\"%ls\"\n",file_name); 
    } 
} 
_wclosedir(dir); 

} 

我目前使用的是Windows 7 64位系统与代码块16.01

奇怪的部分是,Ubuntu的16.04下相同功能的工作完全正常使用的代码块。

+0

这是正常行为对于Windows控制台,看到http://stackoverflow.com/questions/15827607/writeconsolew-wprintf-and-unicode您需要将代码页更改为一个支持你的字符想要打印 – Richard

回答

0

DIR *dir适用于ANSI,不适用于Unicode。改为使用_WDIR

Windows对打印Unicode的支持有限。在MinGW中使用WriteConsoleW来打印Unicode。例如:

#include <stdio.h> 
#include <dirent.h> 
#include <sys/stat.h> 
#include <windows.h> 

void myprint(const wchar_t* str) 
{ 
    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), str, wcslen(str), NULL, NULL); 
} 

void listFolder(const wchar_t* path) 
{ 
    _WDIR *dir = _wopendir(path); 
    if (!dir) return; 

    struct _wdirent *dp; 
    while ((dp=_wreaddir(dir)) != NULL) 
    { 
     if (wcscmp(dp->d_name, L".") == 0 || wcscmp(dp->d_name, L"..") == 0) 
      continue; 
     myprint(dp->d_name); 
     wprintf(L"\n"); 
    } 
    _wclosedir(dir); 
}