可编译为 UNICODE 和 ANSI 版本的遍历目录树程序_0.1

时间:2022-02-11 12:36:26

路径暂时是写死的

编译两个版本的程序:

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 1024
12 
13 #ifdef _UNICODE
14     #define FMT_D "%ld"
15     #define FMT_S "%ls"
16     #define TXT_FILE "TREE_UTF.txt"
17 #else
18     #define FMT_D "%d"
19     #define FMT_S "%s"
20     #define TXT_FILE "TREE_ASC.txt"
21 #endif
22 
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(".")) == 0
48             || _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         else
62         {
63             //output file list
64             _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