2 * DIR.C - dir internal command.
7 * 01/29/97 (Tim Norman)
10 * 06/13/97 (Tim Norman)
13 * 07/12/97 (Tim Norman)
14 * Fixed bug that caused the root directory to be unlistable
16 * 07/12/97 (Marc Desrochers)
17 * Changed to use maxx, maxy instead of findxy()
20 * Added compatibility for /w in dir
23 * Compatibility for dir/s started
24 * Tested that program finds directories off root fine
27 * do_recurse saves the cwd and also stores it in Root
28 * build_tree adds the cwd to the beginning of its' entries
29 * Program runs fine, added print_tree -- works fine.. as EXE,
30 * program won't work properly as COM.
33 * Found problem that caused COM not to work
37 * added free mem routine
40 * debugged the free mem routine
41 * debugged whole thing some more
43 * ReadDir stores Root name and _Read_Dir does the hard work
44 * PrintDir prints Root and _Print_Dir does the hard work
45 * KillDir kills Root _after_ _Kill_Dir does the hard work
46 * Integrated program into DIR.C(this file) and made some same
50 * Cleaned up code a bit, added comments
53 * Added error checking to my previously added routines
56 * Rewrote recursive functions, again! Most other recursive
57 * functions are now obsolete -- ReadDir, PrintDir, _Print_Dir,
58 * KillDir and _Kill_Dir. do_recurse does what PrintDir did
59 * and _Read_Dir did what it did before along with what _Print_Dir
60 * did. Makes /s a lot faster!
61 * Reports 2 more files/dirs that MS-DOS actually reports
62 * when used in root directory(is this because dir defaults
63 * to look for read only files?)
64 * Added support for /b, /a and /l
65 * Made error message similar to DOS error messages
69 * Added check for /-(switch) to turn off previously defined
71 * Added ability to check for DIRCMD in environment and
76 * Now can dir *.ext/X, no spaces!
79 * error message now found in command.h
81 * 07/08/1998 (John P. Price)
82 * removed extra returns; closer to MSDOS
83 * fixed wide display so that an extra return is not displayed
84 * when there is five filenames in the last line.
87 * Changed error messages
89 * 27-Jul-1998 (John P Price <linux-guru@gcfl.net>)
90 * added config.h include
93 * 04-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
94 * Converted source code to Win32, except recursive dir ("dir /s").
96 * 10-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
97 * Fixed recursive dir ("dir /s").
99 * 14-Dec-1998 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
100 * Converted to Win32 directory functions and
101 * fixed some output bugs. There are still some more ;)
103 * 10-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
104 * Added "/N" and "/4" options, "/O" is a dummy.
105 * Added locale support.
107 * 20-Jan-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
110 * 01-Mar-1999 (Eric Kohl <ekohl@abo.rhein-zeitung.de>)
111 * Replaced all runtime io functions by their Win32 counterparts.
113 * 23-Feb-2001 (Carl Nettelblad <cnettel@hem.passagen.se>)
114 * dir /s now works in deeper trees
116 * 28-Jan-2004 (Michael Fritscher <michael@fritscher.net>)
117 * Fix for /p, so it is working under Windows in GUI-mode, too.
119 * 30-Apr-2004 (Filip Navara <xnavara@volny.cz>)
120 * Fix /w to print long names.
122 * 27-Feb-2005 (Konstantinos Paliouras <squarious@gmail.com>)
123 * Implemented all the switches that were missing, and made
124 * the ros dir very similar to windows dir. Major part of
125 * the code is rewritten. /p is removed, to be rewriten in
131 #include "resource.h"
133 #ifdef INCLUDE_CMD_DIR
137 /* Time Field enumeration */
142 TF_LASTACCESSEDDATE
= 2
145 /* Ordered by enumeration */
155 /* The struct for holding the switches */
156 typedef struct _DirSwitchesFlags
158 BOOL bBareFormat
; /* Bare Format */
159 BOOL bTSeperator
; /* Thousands seperator */
160 BOOL bWideList
; /* Wide list format */
161 BOOL bWideListColSort
; /* Wide list format but sorted by column */
162 BOOL bLowerCase
; /* Uses lower case */
163 BOOL bNewLongList
; /* New long list */
164 BOOL bPause
; /* Pause per page */
165 BOOL bUser
; /* Displays the owner of file */
166 BOOL bRecursive
; /* Displays files in specified directory and all sub */
167 BOOL bShortName
; /* Displays the sort name of files if exist */
168 BOOL b4Digit
; /* Four digit year */
171 DWORD dwAttribVal
; /* The desired state of attribute */
172 DWORD dwAttribMask
; /* Which attributes to check */
173 BOOL bUnSet
; /* A helper flag if "-" was given with the switch */
174 BOOL bParSetted
; /* A helper flag if parameters of switch were given */
175 } stAttribs
; /* Displays files with this attributes only */
178 enum EOrderBy eCriteria
[3]; /* Criterias used to order by */
179 BOOL bCriteriaRev
[3]; /* If the criteria is in reversed order */
180 short sCriteriaCount
; /* The quantity of criterias */
181 BOOL bUnSet
; /* A helper flag if "-" was given with the switch */
182 BOOL bParSetted
; /* A helper flag if parameters of switch were given */
183 } stOrderBy
; /* Ordered by criterias */
186 enum ETimeField eTimeField
; /* The time field that will be used for */
187 BOOL bUnSet
; /* A helper flag if "-" was given with the switch */
188 BOOL bParSetted
; /* A helper flag if parameters of switch were given */
189 } stTimeField
; /* The time field to display or use for sorting */
190 } DIRSWITCHFLAGS
, *LPDIRSWITCHFLAGS
;
193 typedef struct _DIRFINDLISTNODE
195 WIN32_FIND_DATA stFindInfo
;
196 struct _DIRFINDLISTNODE
*ptrNext
;
197 } DIRFINDLISTNODE
, *PDIRFINDLISTNODE
;
201 (*PGETFREEDISKSPACEEX
)(LPCTSTR
, PULARGE_INTEGER
, PULARGE_INTEGER
, PULARGE_INTEGER
);
204 /* Globally save the # of dirs, files and bytes,
205 * probabaly later pass them to functions. Rob Lake */
206 static ULONG recurse_dir_cnt
;
207 static ULONG recurse_file_cnt
;
208 static ULARGE_INTEGER recurse_bytes
;
214 * displays help screen for dir
217 static VOID
DirHelp(VOID
)
219 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
220 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP1
, szMsg
, RC_STRING_MAX_SIZE
);
229 * Parse the parameters and switches of the command line and exports them
232 DirReadParam(LPTSTR Line
, /* [IN] The line with the parameters & switches */
233 LPTSTR
*param
, /* [OUT] The parameters after parsing */
234 LPDIRSWITCHFLAGS lpFlags
) /* [IN/OUT] The flags after calculating switches */
236 TCHAR cCurSwitch
; /* The current switch */
237 TCHAR cCurChar
; /* Current examing character */
238 TCHAR cCurUChar
; /* Current upper examing character */
239 BOOL bNegative
; /* Negative switch */
240 BOOL bPNegative
; /* Negative switch parameter */
241 BOOL bIntoQuotes
; /* A flag showing if we are in quotes (") */
242 LPTSTR ptrLast
; /* A pointer to the last character of param */
244 /* Initialize variables; */
245 cCurSwitch
= _T(' ');
250 /* No parameters yet */
254 /* We suppose that switch parameters
255 were given to avoid setting them to default
256 if the switch was not given */
257 lpFlags
->stAttribs
.bParSetted
= TRUE
;
258 lpFlags
->stOrderBy
.bParSetted
= TRUE
;
259 lpFlags
->stTimeField
.bParSetted
= TRUE
;
261 /* Main Loop (see README_DIR.txt) */
262 /* scan the command line char per char, and we process its char */
265 /* we save current character as it is and its upper case */
267 cCurUChar
= _toupper(*Line
);
269 /* 1st section (see README_DIR.txt) */
270 /* When a switch is expecting */
271 if (cCurSwitch
== _T('/'))
273 if ((cCurUChar
== _T('A')) ||(cCurUChar
== _T('T')) || (cCurUChar
== _T('O')))
275 cCurSwitch
= cCurUChar
;
279 lpFlags
->stAttribs
.bUnSet
= bNegative
;
280 lpFlags
->stAttribs
.bParSetted
= FALSE
;
283 lpFlags
->stTimeField
.bUnSet
= bNegative
;
284 lpFlags
->stTimeField
.bParSetted
= FALSE
;
287 lpFlags
->stOrderBy
.bUnSet
= bNegative
;
288 lpFlags
->stOrderBy
.bParSetted
= FALSE
;
292 else if (cCurUChar
== _T('L'))
293 lpFlags
->bLowerCase
= ! bNegative
;
294 else if (cCurUChar
== _T('B'))
295 lpFlags
->bBareFormat
= ! bNegative
;
296 else if (cCurUChar
== _T('C'))
297 lpFlags
->bTSeperator
= ! bNegative
;
298 else if (cCurUChar
== _T('W'))
299 lpFlags
->bWideList
= ! bNegative
;
300 else if (cCurUChar
== _T('D'))
301 lpFlags
->bWideListColSort
= ! bNegative
;
302 else if (cCurUChar
== _T('N'))
303 lpFlags
->bNewLongList
= ! bNegative
;
304 else if (cCurUChar
== _T('P'))
305 lpFlags
->bPause
= ! bNegative
;
306 else if (cCurUChar
== _T('Q'))
307 lpFlags
->bUser
= ! bNegative
;
308 else if (cCurUChar
== _T('S'))
309 lpFlags
->bRecursive
= ! bNegative
;
310 else if (cCurUChar
== _T('X'))
311 lpFlags
->bShortName
= ! bNegative
;
312 else if (cCurChar
== _T('4'))
313 lpFlags
->b4Digit
= ! bNegative
;
314 else if (cCurChar
== _T('?'))
319 else if (cCurChar
== _T('-'))
325 error_invalid_switch ((TCHAR
)_totupper (*Line
));
329 /* We check if we calculated the negative value and realese the flag */
330 if ((cCurChar
!= _T('-')) && bNegative
)
333 /* if not a,o,t or - option then next parameter is not a switch */
334 if ((cCurSwitch
== _T('/')) && (!bNegative
))
335 cCurSwitch
= _T(' ');
338 else if ((cCurSwitch
== _T(' ')) || (cCurSwitch
== _T('P')))
340 /* 2nd section (see README_DIR.txt) */
341 /* We are expecting parameter or the unknown */
343 if (cCurChar
== _T('/'))
344 cCurSwitch
= _T('/');
346 /* Process a spacer */
347 else if (cCurChar
== _T(' '))
351 cCurSwitch
= _T(' ');
352 if ((*param
) && !(ptrLast
))
357 else if (cCurChar
== _T('\"'))
359 /* Process a quote */
360 bIntoQuotes
= !bIntoQuotes
;
361 if (!bIntoQuotes
) ptrLast
= Line
;
365 /* Process a character for parameter */
366 if ((cCurSwitch
== _T(' ')) && (*param
))
368 error_too_many_parameters(Line
);
371 cCurSwitch
= _T('P');
378 /* 3rd section (see README_DIR.txt) */
379 /* We are waiting for switch parameters */
381 /* Check if there are no more switch parameters */
382 if ((cCurChar
== _T('/')) || ( cCurChar
== _T(' ')))
384 /* Wrong desicion path, reprocess current character */
385 cCurSwitch
= cCurChar
;
388 /* Process parameter switch */
391 case _T('A'): /* Switch parameters for /A (attributes filter) */
392 /* Ok a switch parameter was given */
393 lpFlags
->stAttribs
.bParSetted
= TRUE
;
395 if (cCurChar
== _T(':'))
396 /* =V= dead command, used to make the "if" work */
398 else if(cCurChar
== _T('-'))
400 else if(cCurUChar
== _T('D'))
402 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_DIRECTORY
;
404 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_DIRECTORY
;
406 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_DIRECTORY
;
408 else if(cCurUChar
== _T('R'))
410 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_READONLY
;
412 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_READONLY
;
414 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_READONLY
;
416 else if(cCurUChar
== _T('H'))
418 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_HIDDEN
;
420 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_HIDDEN
;
422 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_HIDDEN
;
424 else if(cCurUChar
== _T('A'))
426 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_ARCHIVE
;
428 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_ARCHIVE
;
430 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_ARCHIVE
;
432 else if(cCurUChar
== _T('S'))
434 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_SYSTEM
;
436 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_SYSTEM
;
438 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_SYSTEM
;
442 error_parameter_format((TCHAR
)_totupper (*Line
));
446 case _T('T'): /* Switch parameters for /T (time field) */
448 /* Ok a switch parameter was given */
449 lpFlags
->stTimeField
.bParSetted
= TRUE
;
451 if (cCurChar
== _T(':'))
452 /* =V= dead command, used to make the "if" work */
454 else if(cCurUChar
== _T('C'))
455 lpFlags
->stTimeField
.eTimeField
= TF_CREATIONDATE
;
456 else if(cCurUChar
== _T('A'))
457 lpFlags
->stTimeField
.eTimeField
= TF_LASTACCESSEDDATE
;
458 else if(cCurUChar
== _T('W'))
459 lpFlags
->stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
462 error_parameter_format((TCHAR
)_totupper (*Line
));
466 case _T('O'): /* Switch parameters for /O (order) */
467 /* Ok a switch parameter was given */
468 lpFlags
->stOrderBy
.bParSetted
= TRUE
;
470 if (cCurChar
== _T(':'))
471 /* <== dead command, used to make the "if" work */
473 else if(cCurChar
== _T('-'))
475 else if(cCurUChar
== _T('N'))
477 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
478 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
479 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_NAME
;
481 else if(cCurUChar
== _T('S'))
483 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
484 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
485 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_SIZE
;
487 else if(cCurUChar
== _T('G'))
489 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
490 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
491 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_DIRECTORY
;
493 else if(cCurUChar
== _T('E'))
495 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
496 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
497 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_EXTENSION
;
499 else if(cCurUChar
== _T('D'))
501 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
502 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
503 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_TIME
;
508 error_parameter_format((TCHAR
)_totupper (*Line
));
514 /* We check if we calculated the negative value and realese the flag */
515 if ((cCurChar
!= _T('-')) && bPNegative
)
521 /* Terminate the parameters */
522 if (ptrLast
) *ptrLast
= 0;
524 /* Calculate the switches with no switch paramater */
525 if (!(lpFlags
->stAttribs
.bParSetted
))
527 lpFlags
->stAttribs
.dwAttribVal
= 0L;
528 lpFlags
->stAttribs
.dwAttribMask
= lpFlags
->stAttribs
.dwAttribVal
;
530 if (!(lpFlags
->stOrderBy
.bParSetted
))
532 lpFlags
->stOrderBy
.sCriteriaCount
= 1;
533 lpFlags
->stOrderBy
.eCriteria
[0] = ORDER_NAME
;
534 lpFlags
->stOrderBy
.bCriteriaRev
[0] = FALSE
;
536 if (!(lpFlags
->stOrderBy
.bParSetted
))
537 lpFlags
->stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
539 /* Calculate the unsetted switches (the "-" prefixed)*/
540 if (lpFlags
->stAttribs
.bUnSet
)
542 lpFlags
->stAttribs
.bUnSet
= FALSE
;
543 lpFlags
->stAttribs
.dwAttribVal
= 0L;
544 lpFlags
->stAttribs
.dwAttribMask
= FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_SYSTEM
;
546 if (lpFlags
->stOrderBy
.bUnSet
)
548 lpFlags
->stOrderBy
.bUnSet
= FALSE
;
549 lpFlags
->stOrderBy
.sCriteriaCount
= 0;
551 if (lpFlags
->stTimeField
.bUnSet
)
553 lpFlags
->stTimeField
.bUnSet
= FALSE
;
554 lpFlags
->stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
563 * extend the filespec, possibly adding wildcards
566 ExtendFilespec (LPTSTR file
)
573 /* if no file spec, change to "*.*" */
574 if (*file
== _T('\0'))
576 _tcscpy (file
, _T("*.*"));
580 /* if starts with . add * in front */
581 if (*file
== _T('.'))
583 memmove (&file
[1], &file
[0], (_tcslen (file
) + 1) * sizeof(TCHAR
));
588 if (!_tcschr (file
, _T('.')))
590 _tcscat (file
, _T(".*"));
594 /* if last character is '.' add '*' */
595 len
= _tcslen (file
);
596 if (file
[len
- 1] == _T('.'))
598 _tcscat (file
, _T("*"));
607 * split the pathspec into drive, directory, and filespec
610 DirParsePathspec (LPTSTR szPathspec
, LPTSTR szPath
, LPTSTR szFilespec
)
612 TCHAR szOrigPath
[MAX_PATH
];
616 BOOL bWildcards
= FALSE
;
618 GetCurrentDirectory (MAX_PATH
, szOrigPath
);
620 /* get the drive and change to it */
621 if (szPathspec
[1] == _T(':'))
623 TCHAR szRootPath
[] = _T("A:");
625 szRootPath
[0] = szPathspec
[0];
626 start
= szPathspec
+ 2;
627 if (!SetCurrentDirectory (szRootPath
))
629 ErrorMessage (GetLastError(), NULL
);
639 /* check for wildcards */
640 for (i
= 0; szPathspec
[i
]; i
++)
642 if (szPathspec
[i
] == _T('*') || szPathspec
[i
] == _T('?'))
646 /* check if this spec is a directory */
649 if (SetCurrentDirectory (szPathspec
))
651 _tcscpy (szFilespec
, _T("*.*"));
653 if (!GetCurrentDirectory (MAX_PATH
, szPath
))
655 szFilespec
[0] = _T('\0');
656 SetCurrentDirectory (szOrigPath
);
657 error_out_of_memory();
661 SetCurrentDirectory (szOrigPath
);
666 /* find the file spec */
667 tmp
= _tcsrchr (start
, _T('\\'));
669 /* if no path is specified */
672 _tcscpy (szFilespec
, start
);
673 ExtendFilespec (szFilespec
);
674 if (!GetCurrentDirectory (MAX_PATH
, szPath
))
676 szFilespec
[0] = _T('\0');
677 SetCurrentDirectory (szOrigPath
);
678 error_out_of_memory();
682 SetCurrentDirectory (szOrigPath
);
686 /* get the filename */
687 _tcscpy (szFilespec
, tmp
+1);
688 ExtendFilespec (szFilespec
);
692 /* change to the root directory */
693 if (!SetCurrentDirectory (_T("\\")))
695 szFilespec
[0] = _T('\0');
696 SetCurrentDirectory (szOrigPath
);
697 error_path_not_found ();
705 /* change to this directory */
706 if (!SetCurrentDirectory (start
))
709 szFilespec
[0] = _T('\0');
710 SetCurrentDirectory (szOrigPath
);
711 error_path_not_found ();
716 /* get the full name of the directory */
717 if (!GetCurrentDirectory (MAX_PATH
, szPath
))
720 szFilespec
[0] = _T('\0');
721 SetCurrentDirectory (szOrigPath
);
722 error_out_of_memory ();
728 SetCurrentDirectory (szOrigPath
);
737 * increment our line if paginating, display message at end of screen
741 IncLine (LPINT pLine
, LPDIRSWITCHFLAGS lpFlags
)
744 CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
;
747 bError
= GetConsoleScreenBufferInfo(hConsole
, &lpConsoleScreenBufferInfo
);
749 WindowHeight
= lpConsoleScreenBufferInfo
.srWindow
.Bottom
- lpConsoleScreenBufferInfo
.srWindow
.Top
;
751 /* That prevents bad behiour if WindowHeight could not be calculated */
754 WindowHeight
= 1000000;
757 if (!(lpFlags
->bPause
))
763 * Because I don't know if WindowsHeight work in all cases,
764 * perhaps then maxy is the right value
766 if (*pLine
>= (int)maxy
- 2 || *pLine
>= WindowHeight
)
769 return (PagePrompt () == PROMPT_BREAK
);
777 * PrintDirectoryHeader
779 * print the header for the dir command
782 PrintDirectoryHeader(LPTSTR szPath
, LPINT pLine
, LPDIRSWITCHFLAGS lpFlags
)
784 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
785 TCHAR szRootName
[MAX_PATH
];
790 if (lpFlags
->bBareFormat
)
793 /* build usable root path */
794 if (szPath
[1] == _T(':') && szPath
[2] == _T('\\'))
797 szRootName
[0] = szPath
[0];
798 szRootName
[1] = _T(':');
799 szRootName
[2] = _T('\\');
802 else if (szPath
[0] == _T('\\') && szPath
[1] == _T('\\'))
805 p
= _tcschr(&szPath
[2], _T('\\'));
808 error_invalid_drive();
811 p
= _tcschr(p
+1, _T('\\'));
814 _tcscpy(szRootName
, szPath
);
815 _tcscat(szRootName
, _T("\\"));
820 _tcscpy(szRootName
, szPath
);
821 _tcscat(szRootName
, _T("\\"));
827 error_invalid_drive();
831 /* get the media ID of the drive */
832 if (!GetVolumeInformation(szRootName
, szVolName
, 80, &dwSerialNr
,
833 NULL
, NULL
, NULL
, 0))
835 error_invalid_drive();
839 /* print drive info */
840 if (szVolName
[0] != _T('\0'))
842 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP2
, szMsg
, RC_STRING_MAX_SIZE
);
843 ConOutPrintf((LPTSTR
)szMsg
, szRootName
[0], szVolName
);
847 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP3
, szMsg
, RC_STRING_MAX_SIZE
);
848 ConOutPrintf(szMsg
, szRootName
[0]);
851 /* print the volume serial number if the return was successful */
852 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP4
, (LPTSTR
) szMsg
, RC_STRING_MAX_SIZE
);
853 ConOutPrintf((LPTSTR
)szMsg
,
864 * insert commas into a number
869 ConvertULong (ULONG num
, LPTSTR des
, INT len
)
886 if (((c
+ 1) % (nNumberGroups
+ 1)) == 0)
887 temp
[30 - c
++] = cThousandSeparator
;
888 temp
[30 - c
++] = (TCHAR
)(num
% 10) + _T('0');
892 for (n
= 0; n
<= c
; n
++)
893 des
[n
] = temp
[31 - c
+ n
];
901 ConvertULargeInteger (ULARGE_INTEGER num
, LPTSTR des
, INT len
, BOOL bPutSeperator
)
907 if (num
.QuadPart
== 0)
916 while (num
.QuadPart
> 0)
918 if ((((c
+ 1) % (nNumberGroups
+ 1)) == 0) && (bPutSeperator
))
919 temp
[30 - c
++] = cThousandSeparator
;
920 temp
[30 - c
++] = (TCHAR
)(num
.QuadPart
% 10) + _T('0');
924 for (n
= 0; n
<= c
; n
++)
925 des
[n
] = temp
[31 - c
+ n
];
933 DirPrintFileDateTime(TCHAR
*lpDate
,
935 LPWIN32_FIND_DATA lpFile
,
936 LPDIRSWITCHFLAGS lpFlags
)
944 /* Select the right time field */
945 switch (lpFlags
->stTimeField
.eTimeField
)
947 case TF_CREATIONDATE
:
948 if (!FileTimeToLocalFileTime(&lpFile
->ftCreationTime
, &ft
))
950 FileTimeToSystemTime(&ft
, &dt
);
953 case TF_LASTACCESSEDDATE
:
954 if (!FileTimeToLocalFileTime(&lpFile
->ftLastAccessTime
, &ft
))
956 FileTimeToSystemTime(&ft
, &dt
);
959 case TF_MODIFIEDDATE
:
960 if (!FileTimeToLocalFileTime(&lpFile
->ftLastWriteTime
, &ft
))
962 FileTimeToSystemTime(&ft
, &dt
);
967 wYear
= (lpFlags
->b4Digit
) ? dt
.wYear
: dt
.wYear
%100;
972 _stprintf (szDate
, _T("%02d%c%02d%c%0*d"),
973 dt
.wMonth
, cDateSeparator
,
974 dt
.wDay
, cDateSeparator
,
975 lpFlags
->b4Digit
?4:2, wYear
);
979 _stprintf (szDate
, _T("%02d%c%02d%c%0*d"),
980 dt
.wDay
, cDateSeparator
, dt
.wMonth
,
981 cDateSeparator
,lpFlags
->b4Digit
?4:2, wYear
);
985 _stprintf (szDate
, _T("%0*d%c%02d%c%02d"),
986 lpFlags
->b4Digit
?4:2, wYear
, cDateSeparator
,
987 dt
.wMonth
, cDateSeparator
, dt
.wDay
);
993 case 0: /* 12 hour format */
995 _stprintf (szTime
,_T(" %02d%c%02u%c"),
996 (dt
.wHour
== 0 ? 12 : (dt
.wHour
<= 12 ? dt
.wHour
: dt
.wHour
- 12)),
998 dt
.wMinute
, (dt
.wHour
<= 11 ? _T('a') : _T('p')));
1001 case 1: /* 24 hour format */
1002 _stprintf (szTime
, _T(" %02d%c%02u"),
1003 dt
.wHour
, cTimeSeparator
, dt
.wMinute
);
1007 _tcscpy(lpDate
, szDate
);
1008 _tcscpy(lpTime
, szTime
);
1013 GetUserDiskFreeSpace(LPCTSTR lpRoot
,
1014 PULARGE_INTEGER lpFreeSpace
)
1016 PGETFREEDISKSPACEEX pGetFreeDiskSpaceEx
;
1017 HINSTANCE hInstance
;
1022 ULARGE_INTEGER TotalNumberOfBytes
, TotalNumberOfFreeBytes
;
1024 lpFreeSpace
->QuadPart
= 0;
1026 hInstance
= LoadLibrary(_T("KERNEL32"));
1027 if (hInstance
!= NULL
)
1029 pGetFreeDiskSpaceEx
= (PGETFREEDISKSPACEEX
)GetProcAddress(hInstance
,
1031 "GetDiskFreeSpaceExW");
1033 "GetDiskFreeSpaceExA");
1035 if (pGetFreeDiskSpaceEx
!= NULL
)
1037 if (pGetFreeDiskSpaceEx(lpRoot
, lpFreeSpace
, &TotalNumberOfBytes
, &TotalNumberOfFreeBytes
) == TRUE
)
1040 FreeLibrary(hInstance
);
1043 GetDiskFreeSpace(lpRoot
,
1049 lpFreeSpace
->QuadPart
= dwSecPerCl
* dwBytPerSec
* dwFreeCl
;
1054 * print_summary: prints dir summary
1055 * Added by Rob Lake 06/17/98 to compact code
1056 * Just copied Tim's Code and patched it a bit
1060 PrintSummary(LPTSTR szPath
,
1063 ULARGE_INTEGER u64Bytes
,
1065 LPDIRSWITCHFLAGS lpFlags
)
1067 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1069 ULARGE_INTEGER uliFree
;
1070 TCHAR szRoot
[] = _T("A:\\");
1073 /* Here we check if we didn't find anything */
1074 if (!(ulFiles
+ ulDirs
))
1076 error_file_not_found();
1080 /* In bare format we don't print results */
1081 if (lpFlags
->bBareFormat
)
1084 /* Print recursive specific results */
1085 if (lpFlags
->bRecursive
)
1087 ConvertULargeInteger(u64Bytes
, szBuffer
, sizeof(szBuffer
), lpFlags
->bTSeperator
);
1089 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP5
, szMsg
, RC_STRING_MAX_SIZE
);
1090 ConOutPrintf(szMsg
,ulFiles
, szBuffer
);
1093 /* Print total directories and freespace */
1094 szRoot
[0] = szPath
[0];
1095 GetUserDiskFreeSpace(szRoot
, &uliFree
);
1096 ConvertULargeInteger(uliFree
, szBuffer
, sizeof(szBuffer
), lpFlags
->bTSeperator
);
1097 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP6
, (LPTSTR
) szMsg
, RC_STRING_MAX_SIZE
);
1098 ConOutPrintf((LPTSTR
)szMsg
,ulDirs
, szBuffer
);
1106 * Get the extension of a filename
1108 TCHAR
* getExt(const TCHAR
* file
)
1111 TCHAR
* tmp
= _tcsrchr(file
, _T('.'));
1112 return tmp
?tmp
+1:"";
1118 * Get the name of the file without extension
1120 static LPTSTR
getName(const TCHAR
* file
, TCHAR
* dest
)
1125 /* Check for "." and ".." folders */
1126 if ((_tcscmp(file
, _T(".")) == 0) ||
1127 (_tcscmp(file
, _T("..")) == 0))
1133 end
= _tcsrchr(file
, _T('.'));
1135 iLen
= _tcslen(file
);
1137 iLen
= (end
- file
);
1140 _tcsncpy(dest
, file
, iLen
);
1141 *(dest
+ iLen
) = _T('\0');
1150 * The function that prints in new style
1153 DirPrintNewList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN]Files' Info */
1154 DWORD dwCount
, /* [IN] The quantity of files */
1155 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1156 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1160 TCHAR szShortName
[15];
1164 ULARGE_INTEGER u64FileSize
;
1166 for (i
= 0;i
< dwCount
;i
++)
1168 /* Calculate size */
1169 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1173 _tcscpy(szSize
, _T("<DIR>"));
1179 u64FileSize
.HighPart
= ptrFiles
[i
]->nFileSizeHigh
;
1180 u64FileSize
.LowPart
= ptrFiles
[i
]->nFileSizeLow
;
1181 ConvertULargeInteger(u64FileSize
, szSize
, 20, lpFlags
->bTSeperator
);
1184 /* Calculate short name */
1185 szShortName
[0] = _T('\0');
1186 if (lpFlags
->bShortName
)
1187 _stprintf(szShortName
, _T(" %-12s"), ptrFiles
[i
]->cAlternateFileName
);
1189 /* Format date and time */
1190 DirPrintFileDateTime(szDate
, szTime
, ptrFiles
[i
], lpFlags
);
1192 /* Print the line */
1193 ConOutPrintf(_T("%10s %-8s %*s%s %s\n"),
1199 ptrFiles
[i
]->cFileName
);
1207 * The function that prints in wide list
1210 DirPrintWideList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1211 DWORD dwCount
, /* [IN] The quantity of files */
1212 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1213 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1219 TCHAR szTempFname
[MAX_PATH
];
1224 /* Calculate longest name */
1226 for (i
= 0; i
< dwCount
; i
++)
1228 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1230 /* Directories need 2 additinal characters for brackets */
1231 if ((_tcslen(ptrFiles
[i
]->cFileName
) + 2) > iLongestName
)
1232 iLongestName
= _tcslen(ptrFiles
[i
]->cFileName
) + 2;
1236 if (_tcslen(ptrFiles
[i
]->cFileName
) > iLongestName
)
1237 iLongestName
= _tcslen(ptrFiles
[i
]->cFileName
);
1241 /* Count the highest number of columns */
1242 GetScreenSize(&iScreenWidth
, 0);
1243 iColumns
= iScreenWidth
/ iLongestName
;
1245 /* Check if there is enough space for spaces between names */
1246 if (((iLongestName
* iColumns
) + iColumns
) >= iScreenWidth
)
1249 /* A last check at iColumns to avoid division by zero */
1253 /* Print Column sorted */
1254 if (lpFlags
->bWideListColSort
)
1256 /* Calculate the lines that will be printed */
1257 // iLines = ceil((float)dwCount/(float)iColumns);
1258 iLines
= dwCount
/ iColumns
;
1260 for (i
= 0;i
< iLines
;i
++)
1262 for (j
= 0; j
< iColumns
; j
++)
1264 temp
= (j
* iLines
) + i
;
1265 if (temp
>= dwCount
)
1268 if (ptrFiles
[temp
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1269 _stprintf(szTempFname
, _T("[%s]"), ptrFiles
[temp
]->cFileName
);
1271 _stprintf(szTempFname
, _T("%s"), ptrFiles
[temp
]->cFileName
);
1273 ConOutPrintf(_T("%-*s"), iLongestName
+ 1 , szTempFname
);
1276 ConOutPrintf(_T("\n"));
1281 /* Print Line sorted */
1282 for (i
= 0; i
< dwCount
; i
++)
1284 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1285 _stprintf(szTempFname
, _T("[%s]"), ptrFiles
[i
]->cFileName
);
1287 _stprintf(szTempFname
, _T("%s"), ptrFiles
[i
]->cFileName
);
1289 ConOutPrintf(_T("%-*s"), iLongestName
+ 1, szTempFname
);
1292 * We print a new line at the end of each column
1293 * except for the case that it is the last item.
1295 if (!((i
+ 1) % iColumns
) && (i
< (dwCount
- 1)))
1296 ConOutPrintf(_T("\n"));
1299 /* Add a new line after the last item */
1300 ConOutPrintf(_T("\n"));
1308 * The function that prints in old style
1311 DirPrintOldList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1312 DWORD dwCount
, /* [IN] The quantity of files */
1313 TCHAR
* szCurPath
, /* [IN] Full path of current directory */
1314 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1316 DWORD i
; /* An indexer for "for"s */
1317 TCHAR szName
[10]; /* The name of file */
1318 TCHAR szExt
[5]; /* The extension of file */
1319 TCHAR szDate
[30],szTime
[30]; /* Used to format time and date */
1320 TCHAR szSize
[30]; /* The size of file */
1321 int iSizeFormat
; /* The format of size field */
1322 ULARGE_INTEGER u64FileSize
; /* The file size */
1324 for(i
= 0;i
< dwCount
;i
++)
1326 /* Broke 8.3 format */
1327 if (*ptrFiles
[i
]->cAlternateFileName
)
1329 /* If the file is long named then we read the alter name */
1330 getName( ptrFiles
[i
]->cAlternateFileName
, szName
);
1331 _tcscpy(szExt
, getExt( ptrFiles
[i
]->cAlternateFileName
));
1335 /* If the file is not long name we read its original name */
1336 getName( ptrFiles
[i
]->cFileName
, szName
);
1337 _tcscpy(szExt
, getExt( ptrFiles
[i
]->cFileName
));
1340 /* Calculate size */
1341 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1343 /* Directory, no size it's a directory*/
1345 _tcscpy(szSize
, _T("<DIR>"));
1351 u64FileSize
.HighPart
= ptrFiles
[i
]->nFileSizeHigh
;
1352 u64FileSize
.LowPart
= ptrFiles
[i
]->nFileSizeLow
;
1353 ConvertULargeInteger(u64FileSize
, szSize
, 20, lpFlags
->bTSeperator
);
1356 /* Format date and time */
1357 DirPrintFileDateTime(szDate
,szTime
,ptrFiles
[i
],lpFlags
);
1359 /* Print the line */
1360 ConOutPrintf(_T("%-8s %-3s %*s %s %s\n"),
1361 szName
, /* The file's 8.3 name */
1362 szExt
, /* The file's 8.3 extension */
1363 iSizeFormat
, /* print format for size column */
1364 szSize
, /* The size of file or "<DIR>" for dirs */
1365 szDate
, /* The date of file/dir */
1366 szTime
); /* The time of file/dir */
1373 * The function that prints in bare format
1376 DirPrintBareList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1377 DWORD dwCount
, /* [IN] The number of files */
1378 LPTSTR lpCurPath
, /* [IN] Full path of current directory */
1379 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1381 TCHAR szFullName
[MAX_PATH
];
1384 for (i
= 0; i
< dwCount
; i
++)
1386 if ((_tcscmp(ptrFiles
[i
]->cFileName
, _T(".")) == 0) ||
1387 (_tcscmp(ptrFiles
[i
]->cFileName
, _T("..")) == 0))
1389 /* at bare format we don't print "." and ".." folder */
1392 if (lpFlags
->bRecursive
)
1394 /* at recursive mode we print full path of file */
1395 _tcscpy(szFullName
, lpCurPath
);
1396 _tcscat(szFullName
, ptrFiles
[i
]->cFileName
);
1397 ConOutPrintf("%s\n", szFullName
);
1401 /* if we are not in recursive mode we print the file names */
1402 ConOutPrintf("%s\n",ptrFiles
[i
]->cFileName
);
1411 * The functions that prints the files list
1414 DirPrintFiles(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1415 DWORD dwCount
, /* [IN] The quantity of files */
1416 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1417 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1419 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1420 TCHAR szTemp
[MAX_PATH
]; /* A buffer to format the directory header */
1422 /* Print directory header */
1423 _tcscpy(szTemp
, szCurPath
);
1425 /* We cut the trailing \ of the full path */
1426 szTemp
[_tcslen(szTemp
)-1] = _T('\0');
1428 /* Condition to print header:
1429 We are not printing in bare format
1430 and if we are in recursive mode... we must have results */
1431 if (!(lpFlags
->bBareFormat
) && !((lpFlags
->bRecursive
) && (dwCount
<= 0)))
1433 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP7
, szMsg
, RC_STRING_MAX_SIZE
);
1434 ConOutPrintf(szMsg
, szTemp
);
1437 if (lpFlags
->bBareFormat
)
1440 DirPrintBareList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1442 else if(lpFlags
->bShortName
)
1444 /* New list style / Short names */
1445 DirPrintNewList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1447 else if(lpFlags
->bWideListColSort
|| lpFlags
->bWideList
)
1450 DirPrintWideList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1452 else if (lpFlags
->bNewLongList
)
1455 DirPrintNewList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1459 /* If nothing is selected old list is the default */
1460 DirPrintOldList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1469 * Compares 2 files based on the order criteria
1472 CompareFiles(LPWIN32_FIND_DATA lpFile1
, /* [IN] A pointer to WIN32_FIND_DATA of file 1 */
1473 LPWIN32_FIND_DATA lpFile2
, /* [IN] A pointer to WIN32_FIND_DATA of file 2 */
1474 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags that we use to list */
1476 ULARGE_INTEGER u64File1
;
1477 ULARGE_INTEGER u64File2
;
1479 long iComp
= 0; /* The comparison result */
1481 /* Calculate critiries by order given from user */
1482 for (i
= 0;i
< lpFlags
->stOrderBy
.sCriteriaCount
;i
++)
1485 /* Calculate criteria */
1486 switch(lpFlags
->stOrderBy
.eCriteria
[i
])
1488 case ORDER_SIZE
: /* Order by size /o:s */
1489 /* concat the 32bit integers to a 64bit */
1490 u64File1
.LowPart
= lpFile1
->nFileSizeLow
;
1491 u64File1
.HighPart
= lpFile1
->nFileSizeHigh
;
1492 u64File2
.LowPart
= lpFile2
->nFileSizeLow
;
1493 u64File2
.HighPart
= lpFile2
->nFileSizeHigh
;
1495 /* In case that differnce is too big for a long */
1496 if (u64File1
.QuadPart
< u64File2
.QuadPart
)
1498 else if (u64File1
.QuadPart
> u64File2
.QuadPart
)
1504 case ORDER_DIRECTORY
: /* Order by directory attribute /o:g */
1505 iComp
= ((lpFile2
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)-
1506 (lpFile1
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
));
1509 case ORDER_EXTENSION
: /* Order by extension name /o:e */
1510 iComp
= _stricmp(getExt(lpFile1
->cFileName
),getExt(lpFile2
->cFileName
));
1513 case ORDER_NAME
: /* Order by filename /o:n */
1514 iComp
= _stricmp(lpFile1
->cFileName
, lpFile2
->cFileName
);
1517 case ORDER_TIME
: /* Order by file's time /o:t */
1518 /* We compare files based on the time field selected by /t */
1519 switch(lpFlags
->stTimeField
.eTimeField
)
1521 case TF_CREATIONDATE
:
1522 /* concat the 32bit integers to a 64bit */
1523 u64File1
.LowPart
= lpFile1
->ftCreationTime
.dwLowDateTime
;
1524 u64File1
.HighPart
= lpFile1
->ftCreationTime
.dwHighDateTime
;
1525 u64File2
.LowPart
= lpFile2
->ftCreationTime
.dwLowDateTime
;
1526 u64File2
.HighPart
= lpFile2
->ftCreationTime
.dwHighDateTime
;
1528 case TF_LASTACCESSEDDATE
:
1529 /* concat the 32bit integers to a 64bit */
1530 u64File1
.LowPart
= lpFile1
->ftLastAccessTime
.dwLowDateTime
;
1531 u64File1
.HighPart
= lpFile1
->ftLastAccessTime
.dwHighDateTime
;
1532 u64File2
.LowPart
= lpFile2
->ftLastAccessTime
.dwLowDateTime
;
1533 u64File2
.HighPart
= lpFile2
->ftLastAccessTime
.dwHighDateTime
;
1535 case TF_MODIFIEDDATE
:
1536 /* concat the 32bit integers to a 64bit */
1537 u64File1
.LowPart
= lpFile1
->ftLastWriteTime
.dwLowDateTime
;
1538 u64File1
.HighPart
= lpFile1
->ftLastWriteTime
.dwHighDateTime
;
1539 u64File2
.LowPart
= lpFile2
->ftLastWriteTime
.dwLowDateTime
;
1540 u64File2
.HighPart
= lpFile2
->ftLastWriteTime
.dwHighDateTime
;
1544 /* In case that differnce is too big for a long */
1545 if (u64File1
.QuadPart
< u64File2
.QuadPart
)
1547 else if (u64File1
.QuadPart
> u64File2
.QuadPart
)
1554 /* Reverse if desired */
1555 if (lpFlags
->stOrderBy
.bCriteriaRev
[i
])
1558 /* If that criteria was enough for distinguishing
1559 the files/dirs,there is no need to calculate the others*/
1560 if (iComp
!= 0) break;
1563 /* Translate the value of iComp to boolean */
1573 * Sort files by the order criterias using quicksort method
1576 QsortFiles(LPWIN32_FIND_DATA ptrArray
[], /* [IN/OUT] The array with file info pointers */
1577 int i
, /* [IN] The index of first item in array */
1578 int j
, /* [IN] The index to last item in array */
1579 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags that we will use to sort */
1581 LPWIN32_FIND_DATA lpTemp
; /* A temporary pointer */
1582 int First
, Last
, Temp
;
1592 if (Way
== CompareFiles(ptrArray
[i
], ptrArray
[j
], lpFlags
))
1594 /* Swap the pointers of the array */
1595 lpTemp
= ptrArray
[i
];
1596 ptrArray
[i
]= ptrArray
[j
];
1597 ptrArray
[j
] = lpTemp
;
1599 /* Swap the indexes for inverting sorting */
1610 QsortFiles(ptrArray
,First
, i
-1, lpFlags
);
1611 QsortFiles(ptrArray
,i
+1,Last
, lpFlags
);
1620 * The functions that does everything except for printing results
1623 DirList(LPTSTR szPath
, /* [IN] The path that dir starts */
1624 LPTSTR szFilespec
, /* [IN] The type of file that we are looking for */
1625 LPINT pLine
, /* FIXME: Maybe used for paginating */
1626 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags of the listing */
1628 HANDLE hSearch
; /* The handle of the search */
1629 HANDLE hRecSearch
; /* The handle for searching recursivly */
1630 WIN32_FIND_DATA wfdFileInfo
; /* The info of file that found */
1631 LPWIN32_FIND_DATA
* ptrFileArray
; /* An array of pointers with all the files */
1632 PDIRFINDLISTNODE ptrStartNode
; /* The pointer to the first node */
1633 PDIRFINDLISTNODE ptrNextNode
; /* A pointer used for relatives refernces */
1634 TCHAR szFullPath
[MAX_PATH
]; /* The full path that we are listing with trailing \ */
1635 TCHAR szFullFileSpec
[MAX_PATH
]; /* The full path with file specs that we ll request\ */
1636 TCHAR szBytes
[20]; /* A string for converting ULARGE integer */
1637 DWORD dwCount
; /* A counter of files found in directory */
1638 DWORD dwCountFiles
; /* Counter for files */
1639 DWORD dwCountDirs
; /* Counter for directories */
1640 ULARGE_INTEGER u64CountBytes
; /* Counter for bytes */
1641 ULARGE_INTEGER u64Temp
; /* A temporary counter */
1642 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1644 /* Initialize Variables */
1645 ptrStartNode
= NULL
;
1650 u64CountBytes
.QuadPart
= 0;
1652 /* Create szFullPath and szFullFileSpec */
1653 _tcscpy (szFullPath
, szPath
);
1654 if (szFullPath
[_tcslen(szFullPath
) - 1] != _T('\\'))
1655 _tcscat (szFullPath
, _T("\\"));
1656 _tcscpy (szFullFileSpec
, szFullPath
);
1657 _tcscat (szFullFileSpec
, szFilespec
);
1659 /* Prepare the linked list, first node is allocated */
1660 ptrStartNode
= malloc(sizeof(DIRFINDLISTNODE
));
1661 if (ptrStartNode
== NULL
)
1664 ConErrPrintf("DEBUG: Cannot allocate memory for ptrStartNode!\n");
1666 return 1; /* Error cannot allocate memory for 1st object */
1668 ptrNextNode
= ptrStartNode
;
1670 /* Collect the results for the current folder */
1671 hSearch
= FindFirstFile(szFullFileSpec
, &wfdFileInfo
);
1674 if (hSearch
!= INVALID_HANDLE_VALUE
)
1676 /* Here we filter all the specified attributes */
1677 if ((wfdFileInfo
.dwFileAttributes
& lpFlags
->stAttribs
.dwAttribMask
)
1678 == (lpFlags
->stAttribs
.dwAttribMask
& lpFlags
->stAttribs
.dwAttribVal
))
1680 ptrNextNode
->ptrNext
= malloc(sizeof(DIRFINDLISTNODE
));
1681 if (ptrNextNode
->ptrNext
== NULL
)
1684 ConErrPrintf("DEBUG: Cannot allocate memory for ptrNextNode->ptrNext!\n");
1686 while (ptrStartNode
)
1688 ptrNextNode
= ptrStartNode
->ptrNext
;
1690 ptrStartNode
= ptrNextNode
;
1696 /* If malloc fails we go to next file in hope it works,
1697 without braking the linked list! */
1698 if (ptrNextNode
->ptrNext
)
1700 /* Copy the info of search at linked list */
1701 memcpy(&ptrNextNode
->ptrNext
->stFindInfo
,
1703 sizeof(WIN32_FIND_DATA
));
1705 /* If lower case is selected do it here */
1706 if (lpFlags
->bLowerCase
)
1708 _tcslwr(ptrNextNode
->ptrNext
->stFindInfo
.cAlternateFileName
);
1709 _tcslwr(ptrNextNode
->ptrNext
->stFindInfo
.cFileName
);
1712 /* Continue at next node at linked list */
1713 ptrNextNode
= ptrNextNode
->ptrNext
;
1716 /* Grab statistics */
1717 if (wfdFileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1726 u64Temp
.HighPart
= wfdFileInfo
.nFileSizeHigh
;
1727 u64Temp
.LowPart
= wfdFileInfo
.nFileSizeLow
;
1728 u64CountBytes
.QuadPart
+= u64Temp
.QuadPart
;
1733 }while(FindNextFile(hSearch
, &wfdFileInfo
));
1736 /* Terminate list */
1737 ptrNextNode
->ptrNext
= NULL
;
1739 /* Calculate and allocate space need for making an array of pointers */
1740 ptrFileArray
= malloc(sizeof(LPWIN32_FIND_DATA
) * dwCount
);
1741 if (ptrFileArray
== NULL
)
1744 ConErrPrintf("DEBUG: Cannot allocate memory for ptrFileArray!\n");
1746 while (ptrStartNode
)
1748 ptrNextNode
= ptrStartNode
->ptrNext
;
1750 ptrStartNode
= ptrNextNode
;
1757 * Create an array of pointers from the linked list
1758 * this will be used to sort and print data, rather than the list
1760 ptrNextNode
= ptrStartNode
;
1762 while (ptrNextNode
->ptrNext
)
1764 *(ptrFileArray
+ dwCount
) = &ptrNextNode
->ptrNext
->stFindInfo
;
1765 ptrNextNode
= ptrNextNode
->ptrNext
;
1769 /* Sort Data if requested*/
1770 if (lpFlags
->stOrderBy
.sCriteriaCount
> 0)
1771 QsortFiles(ptrFileArray
, 0, dwCount
-1,lpFlags
);
1774 DirPrintFiles(ptrFileArray
, dwCount
, szFullPath
, lpFlags
);
1779 /* Print Directory Summary */
1780 /* Condition to print summary is:
1781 If we are not in bare format and if we have results! */
1782 if (!(lpFlags
->bBareFormat
) && (dwCount
> 0))
1784 ConvertULargeInteger(u64CountBytes
, szBytes
, 20, lpFlags
->bTSeperator
);
1785 LoadString(GetModuleHandle(NULL
), STRING_DIR_HELP8
, szMsg
, RC_STRING_MAX_SIZE
);
1786 ConOutPrintf(szMsg
,dwCountFiles
, szBytes
);
1789 /* Add statistics to recursive statistics*/
1790 recurse_dir_cnt
+= dwCountDirs
;
1791 recurse_file_cnt
+= dwCountFiles
;
1792 recurse_bytes
.QuadPart
+= u64CountBytes
.QuadPart
;
1794 /* Do the recursive job if requested
1795 the recursive is be done on ALL(indepent of their attribs)
1796 directoried of the current one.*/
1797 if (lpFlags
->bRecursive
)
1799 /* The new search is involving any *.* file */
1800 _tcscpy(szFullFileSpec
, szFullPath
);
1801 _tcscat(szFullFileSpec
, _T("*.*"));
1802 hRecSearch
= FindFirstFile (szFullFileSpec
, &wfdFileInfo
);
1805 if (hRecSearch
!= INVALID_HANDLE_VALUE
)
1807 /* We search for directories other than "." and ".." */
1808 if ((_tcsicmp(wfdFileInfo
.cFileName
, _T(".")) != 0) &&
1809 (_tcsicmp(wfdFileInfo
.cFileName
, _T("..")) != 0 ) &&
1810 (wfdFileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
))
1812 /* Concat the path and the directory to do recursive */
1813 _tcscpy(szFullFileSpec
, szFullPath
);
1814 _tcscat(szFullFileSpec
, wfdFileInfo
.cFileName
);
1815 /* We do the same for tha folder */
1816 DirList(szFullFileSpec
, szFilespec
, pLine
,lpFlags
);
1819 }while(FindNextFile(hRecSearch
,&wfdFileInfo
));
1820 FindClose(hRecSearch
);
1823 /* Free linked list */
1824 while (ptrStartNode
)
1826 ptrNextNode
= ptrStartNode
->ptrNext
;
1828 ptrStartNode
= ptrNextNode
;
1840 * internal dir command
1842 INT
CommandDir(LPTSTR first
, LPTSTR rest
)
1844 TCHAR dircmd
[256]; /* A variable to store the DIRCMD enviroment variable */
1845 TCHAR szPath
[MAX_PATH
];
1846 TCHAR szFilespec
[MAX_PATH
];
1849 DIRSWITCHFLAGS stFlags
;
1851 /* Initialize variables */
1852 recurse_dir_cnt
= 0L;
1853 recurse_file_cnt
= 0L;
1854 recurse_bytes
.QuadPart
= 0;
1856 /* Initialize Switch Flags < Default switches are setted here!> */
1857 stFlags
.b4Digit
= TRUE
;
1858 stFlags
.bBareFormat
= FALSE
;
1859 stFlags
.bLowerCase
= FALSE
;
1860 stFlags
.bNewLongList
= TRUE
;
1861 stFlags
.bPause
= FALSE
;
1862 stFlags
.bRecursive
= FALSE
;
1863 stFlags
.bShortName
= FALSE
;
1864 stFlags
.bTSeperator
= TRUE
;
1865 stFlags
.bUser
= FALSE
;
1866 stFlags
.bWideList
= FALSE
;
1867 stFlags
.bWideListColSort
= FALSE
;
1868 stFlags
.stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
1869 stFlags
.stTimeField
.bUnSet
= FALSE
;
1870 stFlags
.stAttribs
.dwAttribMask
= FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_SYSTEM
;
1871 stFlags
.stAttribs
.dwAttribVal
= 0L;
1872 stFlags
.stAttribs
.bUnSet
= FALSE
;
1873 stFlags
.stOrderBy
.sCriteriaCount
= 0;
1874 stFlags
.stOrderBy
.bUnSet
= FALSE
;
1876 /* read the parameters from the DIRCMD environment variable */
1877 if (GetEnvironmentVariable (_T("DIRCMD"), dircmd
, 256))
1878 if (!DirReadParam(dircmd
, ¶m
, &stFlags
))
1881 /* read the parameters */
1882 if (!DirReadParam(rest
, ¶m
, &stFlags
))
1885 /* default to current directory */
1889 /* parse the directory info */
1890 if (DirParsePathspec (param
, szPath
, szFilespec
))
1894 Uncomment this to show the final state of switch flags*/
1896 ConOutPrintf("Attributes mask/value %x/%x\n",stFlags.stAttribs.dwAttribMask,stFlags.stAttribs.dwAttribVal );
1897 ConOutPrintf("(B) Bare format : %i\n", stFlags.bBareFormat );
1898 ConOutPrintf("(C) Thousand : %i\n", stFlags.bTSeperator );
1899 ConOutPrintf("(W) Wide list : %i\n", stFlags.bWideList );
1900 ConOutPrintf("(D) Wide list sort by column : %i\n", stFlags.bWideListColSort );
1901 ConOutPrintf("(L) Lowercase : %i\n", stFlags.bLowerCase );
1902 ConOutPrintf("(N) New : %i\n", stFlags.bNewLongList );
1903 ConOutPrintf("(O) Order : %i\n", stFlags.stOrderBy.sCriteriaCount );
1905 for (i =0;i<stFlags.stOrderBy.sCriteriaCount;i++)
1906 ConOutPrintf(" Order Criteria [%i]: %i (Reversed: %i)\n",i, stFlags.stOrderBy.eCriteria[i], stFlags.stOrderBy.bCriteriaRev[i] );
1907 ConOutPrintf("(P) Pause : %i\n", stFlags.bPause );
1908 ConOutPrintf("(Q) Owner : %i\n", stFlags.bUser );
1909 ConOutPrintf("(S) Recursive : %i\n", stFlags.bRecursive );
1910 ConOutPrintf("(T) Time field : %i\n", stFlags.stTimeField.eTimeField );
1911 ConOutPrintf("(X) Short names : %i\n", stFlags.bShortName );
1912 ConOutPrintf("Parameter : %s\n", param );
1915 /* print the header */
1916 if (!stFlags
.bBareFormat
)
1917 if (!PrintDirectoryHeader (szPath
, &nLine
, &stFlags
))
1920 /* do the actual dir */
1921 if (DirList (szPath
, szFilespec
, &nLine
, &stFlags
))
1924 /* print the footer */
1925 PrintSummary(szPath
,