標籤:
路徑暫時是寫死的
編譯兩個版本的程式:
g++ treeT.cpp -municode -D_UNICODE -o treeT_UNI
g++ treeT.cpp -o treeT_ASC
為了觀察ANSI版在遍曆檔案夾如果遇到Unicode字元會發生什麼情況而寫來作對比的
他們都可以接收終端傳送的中文字元
ANSI版:
opendir/readdir 遍曆目錄遇到 UNICODE字元的時候會出問題
UNICODE版:
輸出到stdout的時候,值>128 的UNICODE字元丟失
改為 WriteConsoleW 函數可以解決這個問題
1 #include <iostream> 2 #include <cstdio> 3 #include <fcntl.h> 4 #include <sys/stat.h> 5 #include <dirent.h> 6 #include <tchar.h> 7 #include <cwchar> 8 #include <sys/types.h> 9 #include <cstring>10 11 #define NAME_MAX 102412 13 #ifdef _UNICODE14 #define FMT_D "%ld"15 #define FMT_S "%ls"16 #define TXT_FILE "TREE_UTF.txt"17 #else18 #define FMT_D "%d"19 #define FMT_S "%s"20 #define TXT_FILE "TREE_ASC.txt"21 #endif22 23 void func(TCHAR path[]);24 25 static FILE * fp = _tfopen( _TEXT( TXT_FILE ), _TEXT("wb"));26 27 int _tmain(int argc, TCHAR *argv[] )28 {29 TCHAR pth[] = _TEXT("D:\\Extra");30 func(pth);31 fclose(fp);32 return 0;33 }34 35 void func(TCHAR path[])36 {37 _TDIR * a = _topendir(path);38 _tdirent * dp;39 _TDIR * aa;40 struct _stat stbuf;41 42 TCHAR fullpath[NAME_MAX] = _TEXT("");43 44 while (dp = _treaddir(a))45 {46 if (47 _tcscmp(dp->d_name, _TEXT(".")) == 048 || _tcscmp(dp->d_name, _TEXT("..")) == 0 49 )50 {51 continue;52 }53 54 _stprintf(fullpath, _TEXT(FMT_S "\\" FMT_S), path, dp->d_name);55 _tstat(fullpath, &stbuf);56 57 if ( (stbuf.st_mode & S_IFMT) == S_IFDIR )58 {59 func( fullpath );60 }61 else62 {63 //output file list64 _ftprintf(fp, _TEXT( FMT_D "\t" FMT_S "\r\n"), stbuf.st_mtime, fullpath );65 _ftprintf(stdout, _TEXT( FMT_D "\t" FMT_S "\r\n"), stbuf.st_mtime, fullpath );66 }67 68 }69 _tclosedir(a);70 }71 72
可編譯為 UNICODE 和 ANSI 版本的遍曆分類樹程式_0.1