本帖最后由 523066680 于 2015-12-17 00:09 编辑
代码比较臃肿,又有些多余的功能:支持重定向输出并且保留UNICODE字符
我是给那道题助攻的…… (然并卵!纯粹画蛇添足……
把递归去掉了,只列出参数指定目录的文件 以及 DIR FILE 的类型 、路径信息
重定向输出模式的间隔符为tab,utf16-le
有时间再添加参数选项,以及UNICODE开关吧
编译:g++ source.cpp
使用示例:list .\
输出格式像这样 | #include <cstdio> | | #include <cstdlib> | | #include <cwchar> | | #include <sys/stat.h> | | #include <dirent.h> | | #include <locale.h> | | #include <windows.h> | | #include <time.h> | | | | #define NAME_MAX 1024 | | | | void func(wchar_t path[]); | | void time_to_date(time_t t, wchar_t * d_buf); | | | | static FILE * fp; | | DWORD written = 0; | | static bool g_bRedirect = false; | | | | 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); | | } | | } | | | | int main(int argc, char *argv[] ) | | { | | setlocale( LC_ALL, ".936" ); | | wchar_t wspath[1024] = L""; | | CheckConsoleRedirect(); | | | | if (argc > 1) | | { | | mbstowcs( wspath, argv[1], strlen(argv[1]) ); | | | | if ( wspath[wcslen(wspath)-1] != L'\\' ) | | { | | wspath[wcslen(wspath)] = L'\\'; | | wspath[wcslen(wspath)+1] = L'\x00'; | | } | | | | _WDIR * a; | | DIR * b; | | | | if ( (a = _wopendir(wspath)) == NULL ) | | { | | fprintf(stderr, "Argument is not correct!"); | | } | | else | | { | | func( wspath ); | | fprintf(stderr, "All is done!"); | | } | | } | | else | | { | | fprintf(stderr, "No arguments!"); | | } | | | | return 0; | | } | | | | void func(wchar_t path[]) | | { | | _WDIR * a = _wopendir(path); | | _wdirent * dp; | | _WDIR * aa; | | struct stat stbuf; | | | | wchar_t fullpath[NAME_MAX] = L""; | | | | 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); | | | | wstat(fullpath, &stbuf); | | | | wchar_t full_info[NAME_MAX + 32] = L""; | | wchar_t mt_date[11] = L""; | | time_to_date(stbuf.st_mtime, mt_date); | | | | if ( (stbuf.st_mode & S_IFMT) == S_IFDIR ) | | { | | swprintf(full_info, L"%ls\t<DIR>\t%ls\r\n", mt_date, fullpath ); | | } | | else | | { | | swprintf(full_info, L"%ls\t<FILE>\t%ls\r\n", mt_date, fullpath ); | | } | | console_print( full_info ); | | | | } | | _wclosedir(a); | | } | | | | void time_to_date(time_t t, wchar_t * d_buf) | | { | | struct tm *timeinfo; | | timeinfo = localtime( &t ); | | | | swprintf( | | d_buf, | | L"%04d-%02d-%02d", | | timeinfo->tm_year + 1900, | | timeinfo->tm_mon + 1, | | timeinfo->tm_mday | | ); | | }COPY |
|