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

时间:2023-03-08 18:42:20

路径暂时是写死的

编译两个版本的程序:

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 函数可以解决这个问题

 #include <iostream>
#include <cstdio>
#include <fcntl.h>
#include <sys/stat.h>
#include <dirent.h>
#include <tchar.h>
#include <cwchar>
#include <sys/types.h>
#include <cstring> #define NAME_MAX 1024 #ifdef _UNICODE
#define FMT_D "%ld"
#define FMT_S "%ls"
#define TXT_FILE "TREE_UTF.txt"
#else
#define FMT_D "%d"
#define FMT_S "%s"
#define TXT_FILE "TREE_ASC.txt"
#endif void func(TCHAR path[]); static FILE * fp = _tfopen( _TEXT( TXT_FILE ), _TEXT("wb")); int _tmain(int argc, TCHAR *argv[] )
{
TCHAR pth[] = _TEXT("D:\\Extra");
func(pth);
fclose(fp);
return ;
} void func(TCHAR path[])
{
_TDIR * a = _topendir(path);
_tdirent * dp;
_TDIR * aa;
struct _stat stbuf; TCHAR fullpath[NAME_MAX] = _TEXT(""); while (dp = _treaddir(a))
{
if (
_tcscmp(dp->d_name, _TEXT(".")) ==
|| _tcscmp(dp->d_name, _TEXT("..")) ==
)
{
continue;
} _stprintf(fullpath, _TEXT(FMT_S "\\" FMT_S), path, dp->d_name);
_tstat(fullpath, &stbuf); if ( (stbuf.st_mode & S_IFMT) == S_IFDIR )
{
func( fullpath );
}
else
{
//output file list
_ftprintf(fp, _TEXT( FMT_D "\t" FMT_S "\r\n"), stbuf.st_mtime, fullpath );
_ftprintf(stdout, _TEXT( FMT_D "\t" FMT_S "\r\n"), stbuf.st_mtime, fullpath );
} }
_tclosedir(a);
}