ListV1.3 枚举目录树文件结构以及文件大小

回复
头像
vicyang
版主
版主
帖子: 56
注册时间: 2016年07月21日 20:35
联系:

ListV1.3 枚举目录树文件结构以及文件大小

帖子 vicyang »

支持将 Unicode 文件名输出、重定向。
编译:
g++ -municode "listV1.3.cpp" -o "listV1.3.exe"
/*
Code by:523066680@163.com
2017-01

v1.3 对于超过4G的文件,需要将 stat 改为 _stat64
以及在 print 中将 %ld 改为 %lld
*/

#include <stdio.h>
#include <fcntl.h>
#include <dirent.h>
#include <wchar.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <windows.h>

#define NAME_MAX 10240

void func(wchar_t path[]);
void console_print(const wchar_t str[]);
void CheckConsoleRedirect(void);

DWORD written = 0;
static bool g_bRedirect = false;

int wmain(int argc, wchar_t *argv[] )
{
wchar_t pth[NAME_MAX] = L"D:\\Extra\\";

//首先判断是否为重定向
CheckConsoleRedirect();

if ( argc >= 2 )
{
if ( argv[1][wcslen(argv[1])-1] == '\\' )
swprintf(pth, L"%ls", argv[1] );
else
swprintf(pth, L"%ls\\", argv[1] );
}

func( pth );

return 0;
}

void func( wchar_t path[] )
{
DWORD attr;
_WDIR * a = _wopendir(path);
_wdirent * dp;
_WDIR * aa;
struct _stat64 stbuf;
wchar_t full_info[NAME_MAX] = L"";

WCHAR fullpath[NAME_MAX] = L"";

swprintf(full_info, L"FOLD: %ls\r\n", path );
console_print( full_info );

//打印目录内容
while ( dp = _wreaddir(a) )
{
//排除 当前文件夹 和 上一级 文件夹
if (
( wcscmp(dp->d_name, L"." ) == 0 )
|| ( wcscmp(dp->d_name, L".." ) == 0 )
)
{ continue; }
swprintf(fullpath, L"%ls%ls", path, dp->d_name);
_wstat64(fullpath, &stbuf);
attr = GetFileAttributesW(fullpath);

//排除符号链接类型的文件和目录
if ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) != FILE_ATTRIBUTE_REPARSE_POINT )
{
if ( (attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
{
swprintf(full_info, L"%16ls %ls\r\n", L"DIR", dp->d_name );
console_print( full_info );
}
else
{
swprintf(full_info, L"%16lld %ls\r\n", stbuf.st_size, dp->d_name );
console_print( full_info );
}
}
}
_wclosedir(a);

//递归流程
a = _wopendir(path);
while ( dp = _wreaddir(a) )
{
//排除 当前文件夹 和 上一级 文件夹
if (
( wcscmp(dp->d_name, L"." ) == 0 )
|| ( wcscmp(dp->d_name, L".." ) == 0 )
)
{
continue;
}

swprintf(fullpath, L"%ls%ls", path, dp->d_name);
attr = GetFileAttributesW(fullpath);

//排除符号链接类型的文件和目录
if ( (attr & FILE_ATTRIBUTE_REPARSE_POINT) != FILE_ATTRIBUTE_REPARSE_POINT )
{
if ( (attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY )
{
swprintf(fullpath, L"%ls%ls\\", path, dp->d_name);
func( fullpath );
}
}
}
_wclosedir(a);
}

void console_print(const wchar_t str[])
{
if ( ! g_bRedirect )
{
WriteConsoleW(
GetStdHandle(STD_OUTPUT_HANDLE), str, wcslen(str) , &written, NULL
);
}
else
{
WriteFile(
GetStdHandle(STD_OUTPUT_HANDLE), str, wcslen(str) * sizeof( str[0] ) , &written, NULL
);
}
}

void CheckConsoleRedirect(void)
{
if (!GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &written))
{
g_bRedirect = true;
//WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), "\xFF\xFE", 2, &written, 0);
}
}
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 0 访客