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
128 * 1-Jul-2004 (Brandon Turner <turnerb7@msu.edu>)
129 * Added /p back in using ConOutPrintfPaging
133 #include "resource.h"
135 #ifdef INCLUDE_CMD_DIR
139 /* Time Field enumeration */
144 TF_LASTACCESSEDDATE
= 2
147 /* Ordered by enumeration */
157 /* The struct for holding the switches */
158 typedef struct _DirSwitchesFlags
160 BOOL bBareFormat
; /* Bare Format */
161 BOOL bTSeperator
; /* Thousands seperator */
162 BOOL bWideList
; /* Wide list format */
163 BOOL bWideListColSort
; /* Wide list format but sorted by column */
164 BOOL bLowerCase
; /* Uses lower case */
165 BOOL bNewLongList
; /* New long list */
166 BOOL bPause
; /* Pause per page */
167 BOOL bUser
; /* Displays the owner of file */
168 BOOL bRecursive
; /* Displays files in specified directory and all sub */
169 BOOL bShortName
; /* Displays the sort name of files if exist */
170 BOOL b4Digit
; /* Four digit year */
173 DWORD dwAttribVal
; /* The desired state of attribute */
174 DWORD dwAttribMask
; /* Which attributes to check */
175 BOOL bUnSet
; /* A helper flag if "-" was given with the switch */
176 BOOL bParSetted
; /* A helper flag if parameters of switch were given */
177 } stAttribs
; /* Displays files with this attributes only */
180 enum EOrderBy eCriteria
[3]; /* Criterias used to order by */
181 BOOL bCriteriaRev
[3]; /* If the criteria is in reversed order */
182 short sCriteriaCount
; /* The quantity of criterias */
183 BOOL bUnSet
; /* A helper flag if "-" was given with the switch */
184 BOOL bParSetted
; /* A helper flag if parameters of switch were given */
185 } stOrderBy
; /* Ordered by criterias */
188 enum ETimeField eTimeField
; /* The time field that will be used for */
189 BOOL bUnSet
; /* A helper flag if "-" was given with the switch */
190 BOOL bParSetted
; /* A helper flag if parameters of switch were given */
191 } stTimeField
; /* The time field to display or use for sorting */
192 } DIRSWITCHFLAGS
, *LPDIRSWITCHFLAGS
;
195 typedef struct _DIRFINDLISTNODE
197 WIN32_FIND_DATA stFindInfo
;
198 struct _DIRFINDLISTNODE
*ptrNext
;
199 } DIRFINDLISTNODE
, *PDIRFINDLISTNODE
;
203 (WINAPI
*PGETFREEDISKSPACEEX
)(LPCTSTR
, PULARGE_INTEGER
, PULARGE_INTEGER
, PULARGE_INTEGER
);
206 /* Globally save the # of dirs, files and bytes,
207 * probabaly later pass them to functions. Rob Lake */
208 static ULONG recurse_dir_cnt
;
209 static ULONG recurse_file_cnt
;
210 static ULARGE_INTEGER recurse_bytes
;
216 * displays help screen for dir
222 ConOutResPaging(TRUE
, STRING_DIR_HELP1
);
230 * Parse the parameters and switches of the command line and exports them
233 DirReadParam(LPTSTR Line
, /* [IN] The line with the parameters & switches */
234 LPTSTR
** params
, /* [OUT] The parameters after parsing */
235 LPINT entries
, /* [OUT] The number of parameters after parsing */
236 LPDIRSWITCHFLAGS lpFlags
) /* [IN/OUT] The flags after calculating switches */
238 TCHAR cCurSwitch
; /* The current switch */
239 TCHAR cCurChar
; /* Current examing character */
240 TCHAR cCurUChar
; /* Current upper examing character */
241 BOOL bNegative
; /* Negative switch */
242 BOOL bPNegative
; /* Negative switch parameter */
243 BOOL bIntoQuotes
; /* A flag showing if we are in quotes (") */
244 LPTSTR ptrStart
; /* A pointer to the first character of a parameter */
245 LPTSTR ptrEnd
; /* A pointer to the last character of a parameter */
248 /* Initialize parameter array */
249 *params
= malloc(sizeof(LPTSTR
));
257 /* Initialize variables; */
258 cCurSwitch
= _T(' ');
263 /* We suppose that switch parameters
264 were given to avoid setting them to default
265 if the switch was not given */
266 lpFlags
->stAttribs
.bParSetted
= TRUE
;
267 lpFlags
->stOrderBy
.bParSetted
= TRUE
;
268 lpFlags
->stTimeField
.bParSetted
= TRUE
;
271 /* Main Loop (see README_DIR.txt) */
272 /* scan the command line char per char, and we process its char */
275 /* we save current character as it is and its upper case */
277 cCurUChar
= _totupper(*Line
);
279 /* 1st section (see README_DIR.txt) */
280 /* When a switch is expecting */
281 if (cCurSwitch
== _T('/'))
283 if ((cCurUChar
== _T('A')) ||(cCurUChar
== _T('T')) || (cCurUChar
== _T('O')))
285 cCurSwitch
= cCurUChar
;
289 lpFlags
->stAttribs
.bUnSet
= bNegative
;
290 lpFlags
->stAttribs
.bParSetted
= FALSE
;
293 lpFlags
->stTimeField
.bUnSet
= bNegative
;
294 lpFlags
->stTimeField
.bParSetted
= FALSE
;
297 lpFlags
->stOrderBy
.bUnSet
= bNegative
;
298 lpFlags
->stOrderBy
.bParSetted
= FALSE
;
302 else if (cCurUChar
== _T('L'))
303 lpFlags
->bLowerCase
= ! bNegative
;
304 else if (cCurUChar
== _T('B'))
305 lpFlags
->bBareFormat
= ! bNegative
;
306 else if (cCurUChar
== _T('C'))
307 lpFlags
->bTSeperator
= ! bNegative
;
308 else if (cCurUChar
== _T('W'))
309 lpFlags
->bWideList
= ! bNegative
;
310 else if (cCurUChar
== _T('D'))
311 lpFlags
->bWideListColSort
= ! bNegative
;
312 else if (cCurUChar
== _T('N'))
313 lpFlags
->bNewLongList
= ! bNegative
;
314 else if (cCurUChar
== _T('P'))
315 lpFlags
->bPause
= ! bNegative
;
316 else if (cCurUChar
== _T('Q'))
317 lpFlags
->bUser
= ! bNegative
;
318 else if (cCurUChar
== _T('S'))
319 lpFlags
->bRecursive
= ! bNegative
;
320 else if (cCurUChar
== _T('X'))
321 lpFlags
->bShortName
= ! bNegative
;
322 else if (cCurChar
== _T('4'))
323 lpFlags
->b4Digit
= ! bNegative
;
324 else if (cCurChar
== _T('?'))
329 else if (cCurChar
== _T('-'))
335 error_invalid_switch ((TCHAR
)_totupper (*Line
));
339 /* We check if we calculated the negative value and realese the flag */
340 if ((cCurChar
!= _T('-')) && bNegative
)
343 /* if not a,o,t or - option then next parameter is not a switch */
344 if ((cCurSwitch
== _T('/')) && (!bNegative
))
345 cCurSwitch
= _T(' ');
348 else if ((cCurSwitch
== _T(' ')) || (cCurSwitch
== _T('P')))
350 /* 2nd section (see README_DIR.txt) */
351 /* We are expecting parameter or the unknown */
353 if (cCurChar
== _T('/'))
354 cCurSwitch
= _T('/');
356 /* Process a spacer */
357 else if (cCurChar
== _T(' '))
361 cCurSwitch
= _T(' ');
362 if(ptrStart
&& ptrEnd
)
364 temp
= malloc((ptrEnd
- ptrStart
) + 2 * sizeof (TCHAR
));
367 memcpy(temp
, ptrStart
, (ptrEnd
- ptrStart
) + 2 * sizeof (TCHAR
));
368 temp
[(ptrEnd
- ptrStart
+ 1)] = _T('\0');
369 if(!add_entry(entries
, params
, temp
))
384 else if (cCurChar
== _T('\"'))
386 /* Process a quote */
387 bIntoQuotes
= !bIntoQuotes
;
393 /* Process a character for parameter */
394 if ((cCurSwitch
== _T(' ')) && ptrStart
&& ptrEnd
)
396 temp
= malloc((ptrEnd
- ptrStart
) + 2 * sizeof (TCHAR
));
399 memcpy(temp
, ptrStart
, (ptrEnd
- ptrStart
) + 2 * sizeof (TCHAR
));
400 temp
[(ptrEnd
- ptrStart
+ 1)] = _T('\0');
401 if(!add_entry(entries
, params
, temp
))
413 cCurSwitch
= _T('P');
415 ptrStart
= ptrEnd
= Line
;
421 /* 3rd section (see README_DIR.txt) */
422 /* We are waiting for switch parameters */
424 /* Check if there are no more switch parameters */
425 if ((cCurChar
== _T('/')) || ( cCurChar
== _T(' ')))
427 /* Wrong desicion path, reprocess current character */
428 cCurSwitch
= cCurChar
;
431 /* Process parameter switch */
434 case _T('A'): /* Switch parameters for /A (attributes filter) */
435 /* Ok a switch parameter was given */
436 lpFlags
->stAttribs
.bParSetted
= TRUE
;
438 if (cCurChar
== _T(':'))
439 /* =V= dead command, used to make the "if" work */
441 else if(cCurChar
== _T('-'))
443 else if(cCurUChar
== _T('D'))
445 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_DIRECTORY
;
447 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_DIRECTORY
;
449 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_DIRECTORY
;
451 else if(cCurUChar
== _T('R'))
453 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_READONLY
;
455 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_READONLY
;
457 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_READONLY
;
459 else if(cCurUChar
== _T('H'))
461 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_HIDDEN
;
463 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_HIDDEN
;
465 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_HIDDEN
;
467 else if(cCurUChar
== _T('A'))
469 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_ARCHIVE
;
471 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_ARCHIVE
;
473 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_ARCHIVE
;
475 else if(cCurUChar
== _T('S'))
477 lpFlags
->stAttribs
.dwAttribMask
|= FILE_ATTRIBUTE_SYSTEM
;
479 lpFlags
->stAttribs
.dwAttribVal
&= ~FILE_ATTRIBUTE_SYSTEM
;
481 lpFlags
->stAttribs
.dwAttribVal
|= FILE_ATTRIBUTE_SYSTEM
;
485 error_parameter_format((TCHAR
)_totupper (*Line
));
489 case _T('T'): /* Switch parameters for /T (time field) */
491 /* Ok a switch parameter was given */
492 lpFlags
->stTimeField
.bParSetted
= TRUE
;
494 if (cCurChar
== _T(':'))
495 /* =V= dead command, used to make the "if" work */
497 else if(cCurUChar
== _T('C'))
498 lpFlags
->stTimeField
.eTimeField
= TF_CREATIONDATE
;
499 else if(cCurUChar
== _T('A'))
500 lpFlags
->stTimeField
.eTimeField
= TF_LASTACCESSEDDATE
;
501 else if(cCurUChar
== _T('W'))
502 lpFlags
->stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
505 error_parameter_format((TCHAR
)_totupper (*Line
));
509 case _T('O'): /* Switch parameters for /O (order) */
510 /* Ok a switch parameter was given */
511 lpFlags
->stOrderBy
.bParSetted
= TRUE
;
513 if (cCurChar
== _T(':'))
514 /* <== dead command, used to make the "if" work */
516 else if(cCurChar
== _T('-'))
518 else if(cCurUChar
== _T('N'))
520 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
521 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
522 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_NAME
;
524 else if(cCurUChar
== _T('S'))
526 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
527 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
528 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_SIZE
;
530 else if(cCurUChar
== _T('G'))
532 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
533 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
534 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_DIRECTORY
;
536 else if(cCurUChar
== _T('E'))
538 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
539 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
540 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_EXTENSION
;
542 else if(cCurUChar
== _T('D'))
544 if (lpFlags
->stOrderBy
.sCriteriaCount
< 3) lpFlags
->stOrderBy
.sCriteriaCount
++;
545 lpFlags
->stOrderBy
.bCriteriaRev
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = bPNegative
;
546 lpFlags
->stOrderBy
.eCriteria
[lpFlags
->stOrderBy
.sCriteriaCount
- 1] = ORDER_TIME
;
551 error_parameter_format((TCHAR
)_totupper (*Line
));
557 /* We check if we calculated the negative value and realese the flag */
558 if ((cCurChar
!= _T('-')) && bPNegative
)
564 /* Terminate the parameters */
565 if(ptrStart
&& ptrEnd
)
567 temp
= malloc((ptrEnd
- ptrStart
) + 2 * sizeof (TCHAR
));
570 memcpy(temp
, ptrStart
, (ptrEnd
- ptrStart
) + 2 * sizeof (TCHAR
));
571 temp
[(ptrEnd
- ptrStart
+ 1)] = _T('\0');
572 if(!add_entry(entries
, params
, temp
))
585 /* Calculate the switches with no switch paramater */
586 if (!(lpFlags
->stAttribs
.bParSetted
))
588 lpFlags
->stAttribs
.dwAttribVal
= 0L;
589 lpFlags
->stAttribs
.dwAttribMask
= lpFlags
->stAttribs
.dwAttribVal
;
591 if (!(lpFlags
->stOrderBy
.bParSetted
))
593 lpFlags
->stOrderBy
.sCriteriaCount
= 1;
594 lpFlags
->stOrderBy
.eCriteria
[0] = ORDER_NAME
;
595 lpFlags
->stOrderBy
.bCriteriaRev
[0] = FALSE
;
597 if (!(lpFlags
->stOrderBy
.bParSetted
))
598 lpFlags
->stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
600 /* Calculate the unsetted switches (the "-" prefixed)*/
601 if (lpFlags
->stAttribs
.bUnSet
)
603 lpFlags
->stAttribs
.bUnSet
= FALSE
;
604 lpFlags
->stAttribs
.dwAttribVal
= 0L;
605 lpFlags
->stAttribs
.dwAttribMask
= FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_SYSTEM
;
607 if (lpFlags
->stOrderBy
.bUnSet
)
609 lpFlags
->stOrderBy
.bUnSet
= FALSE
;
610 lpFlags
->stOrderBy
.sCriteriaCount
= 0;
612 if (lpFlags
->stTimeField
.bUnSet
)
614 lpFlags
->stTimeField
.bUnSet
= FALSE
;
615 lpFlags
->stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
624 * extend the filespec, possibly adding wildcards
627 ExtendFilespec (LPTSTR file
)
635 /* if no file spec, change to "*.*" */
636 if (*file
== _T('\0'))
638 _tcscpy (file
, _T("*.*"));
642 // add support for *.
643 if ((file
[0] == _T('*')) && (file
[1] == _T('.') ))
648 /* if starts with . add * in front */
649 if (*file
== _T('.'))
651 memmove (&file
[1], &file
[0], (_tcslen (file
) + 1) * sizeof(TCHAR
));
656 if (!_tcschr (file
, _T('.')))
658 _tcscat (file
, _T(".*"));
664 /* if last character is '.' add '*' */
665 len
= _tcslen (file
);
666 if (file
[len
- 1] == _T('.'))
668 _tcscat (file
, _T("*"));
677 * split the pathspec into drive, directory, and filespec
680 DirParsePathspec (LPTSTR szPathspec
, LPTSTR szPath
, LPTSTR szFilespec
)
682 TCHAR szOrigPath
[MAX_PATH
];
686 BOOL bWildcards
= FALSE
;
688 GetCurrentDirectory (MAX_PATH
, szOrigPath
);
690 /* get the drive and change to it */
691 if (szPathspec
[1] == _T(':'))
693 TCHAR szRootPath
[] = _T("A:");
695 szRootPath
[0] = szPathspec
[0];
696 start
= szPathspec
+ 2;
697 if (!SetCurrentDirectory (szRootPath
))
699 ErrorMessage (GetLastError(), NULL
);
709 /* check for wildcards */
710 for (i
= 0; szPathspec
[i
]; i
++)
712 if (szPathspec
[i
] == _T('*') || szPathspec
[i
] == _T('?'))
716 /* check if this spec is a directory */
719 if (SetCurrentDirectory (szPathspec
))
721 _tcscpy (szFilespec
, _T("*.*"));
723 if (!GetCurrentDirectory (MAX_PATH
, szPath
))
725 szFilespec
[0] = _T('\0');
726 SetCurrentDirectory (szOrigPath
);
727 error_out_of_memory();
731 SetCurrentDirectory (szOrigPath
);
736 /* find the file spec */
737 tmp
= _tcsrchr (start
, _T('\\'));
739 /* if no path is specified */
742 _tcscpy (szFilespec
, start
);
743 ExtendFilespec (szFilespec
);
744 if (!GetCurrentDirectory (MAX_PATH
, szPath
))
746 szFilespec
[0] = _T('\0');
747 SetCurrentDirectory (szOrigPath
);
748 error_out_of_memory();
752 SetCurrentDirectory (szOrigPath
);
756 /* get the filename */
757 _tcscpy (szFilespec
, tmp
+1);
758 ExtendFilespec (szFilespec
);
762 /* change to the root directory */
763 if (!SetCurrentDirectory (_T("\\")))
765 szFilespec
[0] = _T('\0');
766 SetCurrentDirectory (szOrigPath
);
767 error_path_not_found ();
775 /* change to this directory */
776 if (!SetCurrentDirectory (start
))
779 szFilespec
[0] = _T('\0');
780 SetCurrentDirectory (szOrigPath
);
781 error_path_not_found ();
786 /* get the full name of the directory */
787 if (!GetCurrentDirectory (MAX_PATH
, szPath
))
790 szFilespec
[0] = _T('\0');
791 SetCurrentDirectory (szOrigPath
);
792 error_out_of_memory ();
798 SetCurrentDirectory (szOrigPath
);
807 * increment our line if paginating, display message at end of screen
811 IncLine (LPINT pLine
, LPDIRSWITCHFLAGS lpFlags
)
814 CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
;
817 bError
= GetConsoleScreenBufferInfo(hConsole
, &lpConsoleScreenBufferInfo
);
819 WindowHeight
= lpConsoleScreenBufferInfo
.srWindow
.Bottom
- lpConsoleScreenBufferInfo
.srWindow
.Top
;
821 /* That prevents bad behiour if WindowHeight could not be calculated */
824 WindowHeight
= 1000000;
827 if (!(lpFlags
->bPause
))
833 * Because I don't know if WindowsHeight work in all cases,
834 * perhaps then maxy is the right value
836 if (*pLine
>= (int)maxy
- 2 || *pLine
>= WindowHeight
)
839 return (PagePrompt () == PROMPT_BREAK
);
847 * PrintDirectoryHeader
849 * print the header for the dir command
852 PrintDirectoryHeader(LPTSTR szPath
, LPINT pLine
, LPDIRSWITCHFLAGS lpFlags
)
854 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
855 TCHAR szRootName
[MAX_PATH
];
860 if (lpFlags
->bBareFormat
)
863 /* build usable root path */
864 if (szPath
[1] == _T(':') && szPath
[2] == _T('\\'))
867 szRootName
[0] = szPath
[0];
868 szRootName
[1] = _T(':');
869 szRootName
[2] = _T('\\');
872 else if (szPath
[0] == _T('\\') && szPath
[1] == _T('\\'))
875 p
= _tcschr(&szPath
[2], _T('\\'));
878 error_invalid_drive();
881 p
= _tcschr(p
+1, _T('\\'));
884 _tcscpy(szRootName
, szPath
);
885 _tcscat(szRootName
, _T("\\"));
890 _tcscpy(szRootName
, szPath
);
891 _tcscat(szRootName
, _T("\\"));
897 error_invalid_drive();
901 /* get the media ID of the drive */
902 if (!GetVolumeInformation(szRootName
, szVolName
, 80, &dwSerialNr
,
903 NULL
, NULL
, NULL
, 0))
905 error_invalid_drive();
909 /* print drive info */
910 if (szVolName
[0] != _T('\0'))
912 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP2
, szMsg
, RC_STRING_MAX_SIZE
);
913 //needs to have first paramter as TRUE because
914 //this is the first output and need to clear the static
916 ConOutPrintfPaging(TRUE
,szMsg
, szRootName
[0], szVolName
);
918 ConOutPrintf(szMsg
, szRootName
[0], szVolName
);
923 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP3
, szMsg
, RC_STRING_MAX_SIZE
);
925 ConOutPrintfPaging(TRUE
,szMsg
, szRootName
[0]);
927 ConOutPrintf(szMsg
, szRootName
[0]);
930 /* print the volume serial number if the return was successful */
931 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP4
, (LPTSTR
) szMsg
, RC_STRING_MAX_SIZE
);
933 ConOutPrintfPaging(FALSE
,szMsg
,
949 * insert commas into a number
954 ConvertULong (ULONG num
, LPTSTR des
, INT len
)
971 if (((c
+ 1) % (nNumberGroups
+ 1)) == 0)
972 temp
[30 - c
++] = cThousandSeparator
;
973 temp
[30 - c
++] = (TCHAR
)(num
% 10) + _T('0');
977 for (n
= 0; n
<= c
; n
++)
978 des
[n
] = temp
[31 - c
+ n
];
986 DirPrintFileDateTime(TCHAR
*lpDate
,
988 LPWIN32_FIND_DATA lpFile
,
989 LPDIRSWITCHFLAGS lpFlags
)
997 /* Select the right time field */
998 switch (lpFlags
->stTimeField
.eTimeField
)
1000 case TF_CREATIONDATE
:
1001 if (!FileTimeToLocalFileTime(&lpFile
->ftCreationTime
, &ft
))
1003 FileTimeToSystemTime(&ft
, &dt
);
1006 case TF_LASTACCESSEDDATE
:
1007 if (!FileTimeToLocalFileTime(&lpFile
->ftLastAccessTime
, &ft
))
1009 FileTimeToSystemTime(&ft
, &dt
);
1012 case TF_MODIFIEDDATE
:
1013 if (!FileTimeToLocalFileTime(&lpFile
->ftLastWriteTime
, &ft
))
1015 FileTimeToSystemTime(&ft
, &dt
);
1020 wYear
= (lpFlags
->b4Digit
) ? dt
.wYear
: dt
.wYear
%100;
1021 switch (nDateFormat
)
1023 case 0: /* mmddyy */
1025 _stprintf (szDate
, _T("%02d%c%02d%c%0*d"),
1026 dt
.wMonth
, cDateSeparator
,
1027 dt
.wDay
, cDateSeparator
,
1028 lpFlags
->b4Digit
?4:2, wYear
);
1031 case 1: /* ddmmyy */
1032 _stprintf (szDate
, _T("%02d%c%02d%c%0*d"),
1033 dt
.wDay
, cDateSeparator
, dt
.wMonth
,
1034 cDateSeparator
,lpFlags
->b4Digit
?4:2, wYear
);
1037 case 2: /* yymmdd */
1038 _stprintf (szDate
, _T("%0*d%c%02d%c%02d"),
1039 lpFlags
->b4Digit
?4:2, wYear
, cDateSeparator
,
1040 dt
.wMonth
, cDateSeparator
, dt
.wDay
);
1044 switch (nTimeFormat
)
1046 case 0: /* 12 hour format */
1048 _stprintf (szTime
,_T(" %02d%c%02u%c"),
1049 (dt
.wHour
== 0 ? 12 : (dt
.wHour
<= 12 ? dt
.wHour
: dt
.wHour
- 12)),
1051 dt
.wMinute
, (dt
.wHour
<= 11 ? _T('a') : _T('p')));
1054 case 1: /* 24 hour format */
1055 _stprintf (szTime
, _T(" %02d%c%02u"),
1056 dt
.wHour
, cTimeSeparator
, dt
.wMinute
);
1060 _tcscpy(lpDate
, szDate
);
1061 _tcscpy(lpTime
, szTime
);
1066 GetUserDiskFreeSpace(LPCTSTR lpRoot
,
1067 PULARGE_INTEGER lpFreeSpace
)
1069 PGETFREEDISKSPACEEX pGetFreeDiskSpaceEx
;
1070 HINSTANCE hInstance
;
1075 ULARGE_INTEGER TotalNumberOfBytes
, TotalNumberOfFreeBytes
;
1077 lpFreeSpace
->QuadPart
= 0;
1079 hInstance
= LoadLibrary(_T("KERNEL32"));
1080 if (hInstance
!= NULL
)
1082 pGetFreeDiskSpaceEx
= (PGETFREEDISKSPACEEX
)GetProcAddress(hInstance
,
1084 "GetDiskFreeSpaceExW");
1086 "GetDiskFreeSpaceExA");
1088 if (pGetFreeDiskSpaceEx
!= NULL
)
1090 if (pGetFreeDiskSpaceEx(lpRoot
, lpFreeSpace
, &TotalNumberOfBytes
, &TotalNumberOfFreeBytes
) == TRUE
)
1093 FreeLibrary(hInstance
);
1096 GetDiskFreeSpace(lpRoot
,
1102 lpFreeSpace
->QuadPart
= dwSecPerCl
* dwBytPerSec
* dwFreeCl
;
1107 * print_summary: prints dir summary
1108 * Added by Rob Lake 06/17/98 to compact code
1109 * Just copied Tim's Code and patched it a bit
1113 PrintSummary(LPTSTR szPath
,
1116 ULARGE_INTEGER u64Bytes
,
1118 LPDIRSWITCHFLAGS lpFlags
)
1120 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1122 ULARGE_INTEGER uliFree
;
1123 TCHAR szRoot
[] = _T("A:\\");
1126 /* Here we check if we didn't find anything */
1127 if (!(ulFiles
+ ulDirs
))
1129 error_file_not_found();
1133 /* In bare format we don't print results */
1134 if (lpFlags
->bBareFormat
)
1137 /* Print recursive specific results */
1138 if (lpFlags
->bRecursive
)
1140 ConvertULargeInteger(u64Bytes
, szBuffer
, sizeof(szBuffer
), lpFlags
->bTSeperator
);
1142 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP5
, szMsg
, RC_STRING_MAX_SIZE
);
1144 ConOutPrintfPaging(FALSE
,szMsg
,ulFiles
, szBuffer
);
1146 ConOutPrintf(szMsg
,ulFiles
, szBuffer
);
1149 /* Print File Summary */
1150 /* Condition to print summary is:
1151 If we are not in bare format and if we have results! */
1154 ConvertULargeInteger(u64Bytes
, szBuffer
, 20, lpFlags
->bTSeperator
);
1155 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP8
, szMsg
, RC_STRING_MAX_SIZE
);
1157 ConOutPrintfPaging(FALSE
,szMsg
,ulFiles
, szBuffer
);
1159 ConOutPrintf(szMsg
,ulFiles
, szBuffer
);
1163 /* Print total directories and freespace */
1164 szRoot
[0] = szPath
[0];
1165 GetUserDiskFreeSpace(szRoot
, &uliFree
);
1166 ConvertULargeInteger(uliFree
, szBuffer
, sizeof(szBuffer
), lpFlags
->bTSeperator
);
1167 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP6
, (LPTSTR
) szMsg
, RC_STRING_MAX_SIZE
);
1169 ConOutPrintfPaging(FALSE
,szMsg
,ulDirs
, szBuffer
);
1171 ConOutPrintf(szMsg
,ulDirs
, szBuffer
);
1179 * Get the extension of a filename
1181 TCHAR
* getExt(const TCHAR
* file
)
1183 static TCHAR
*NoExt
= _T("");
1184 TCHAR
* lastdot
= _tcsrchr(file
, _T('.'));
1185 return (lastdot
!= NULL
? lastdot
+ 1 : NoExt
);
1191 * Get the name of the file without extension
1194 getName(const TCHAR
* file
, TCHAR
* dest
)
1199 /* Check for "." and ".." folders */
1200 if ((_tcscmp(file
, _T(".")) == 0) ||
1201 (_tcscmp(file
, _T("..")) == 0))
1207 end
= _tcsrchr(file
, _T('.'));
1209 iLen
= _tcslen(file
);
1211 iLen
= (end
- file
);
1214 _tcsncpy(dest
, file
, iLen
);
1215 *(dest
+ iLen
) = _T('\0');
1224 * The function that prints in new style
1227 DirPrintNewList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN]Files' Info */
1228 DWORD dwCount
, /* [IN] The quantity of files */
1229 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1230 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1234 TCHAR szShortName
[15];
1238 ULARGE_INTEGER u64FileSize
;
1240 for (i
= 0;i
< dwCount
;i
++)
1242 /* Calculate size */
1243 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1247 _tcscpy(szSize
, _T("<DIR>"));
1253 u64FileSize
.HighPart
= ptrFiles
[i
]->nFileSizeHigh
;
1254 u64FileSize
.LowPart
= ptrFiles
[i
]->nFileSizeLow
;
1255 ConvertULargeInteger(u64FileSize
, szSize
, 20, lpFlags
->bTSeperator
);
1258 /* Calculate short name */
1259 szShortName
[0] = _T('\0');
1260 if (lpFlags
->bShortName
)
1261 _stprintf(szShortName
, _T(" %-12s"), ptrFiles
[i
]->cAlternateFileName
);
1263 /* Format date and time */
1264 DirPrintFileDateTime(szDate
, szTime
, ptrFiles
[i
], lpFlags
);
1266 /* Print the line */
1268 ConOutPrintfPaging(FALSE
,_T("%10s %-8s %*s%s %s\n"),
1274 ptrFiles
[i
]->cFileName
);
1276 ConOutPrintf(_T("%10s %-8s %*s%s %s\n"),
1282 ptrFiles
[i
]->cFileName
);
1290 * The function that prints in wide list
1293 DirPrintWideList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1294 DWORD dwCount
, /* [IN] The quantity of files */
1295 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1296 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1302 TCHAR szTempFname
[MAX_PATH
];
1307 /* Calculate longest name */
1309 for (i
= 0; i
< dwCount
; i
++)
1311 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1313 /* Directories need 2 additinal characters for brackets */
1314 if ((_tcslen(ptrFiles
[i
]->cFileName
) + 2) > iLongestName
)
1315 iLongestName
= _tcslen(ptrFiles
[i
]->cFileName
) + 2;
1319 if (_tcslen(ptrFiles
[i
]->cFileName
) > iLongestName
)
1320 iLongestName
= _tcslen(ptrFiles
[i
]->cFileName
);
1324 /* Count the highest number of columns */
1325 GetScreenSize(&iScreenWidth
, 0);
1326 iColumns
= iScreenWidth
/ iLongestName
;
1328 /* Check if there is enough space for spaces between names */
1329 if (((iLongestName
* iColumns
) + iColumns
) >= (UINT
)iScreenWidth
)
1332 /* A last check at iColumns to avoid division by zero */
1336 /* Print Column sorted */
1337 if (lpFlags
->bWideListColSort
)
1339 /* Calculate the lines that will be printed */
1340 // iLines = ceil((float)dwCount/(float)iColumns);
1341 iLines
= (USHORT
)(dwCount
/ iColumns
);
1343 for (i
= 0;i
< iLines
;i
++)
1345 for (j
= 0; j
< iColumns
; j
++)
1347 temp
= (j
* iLines
) + i
;
1348 if (temp
>= dwCount
)
1351 if (ptrFiles
[temp
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1352 _stprintf(szTempFname
, _T("[%s]"), ptrFiles
[temp
]->cFileName
);
1354 _stprintf(szTempFname
, _T("%s"), ptrFiles
[temp
]->cFileName
);
1357 ConOutPrintfPaging(FALSE
,_T("%-*s"), iLongestName
+ 1 , szTempFname
);
1359 ConOutPrintf(_T("%-*s"), iLongestName
+ 1 , szTempFname
);
1363 ConOutPrintfPaging(FALSE
,_T("\n"));
1365 ConOutPrintf(_T("\n"));
1370 /* Print Line sorted */
1371 for (i
= 0; i
< dwCount
; i
++)
1373 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1374 _stprintf(szTempFname
, _T("[%s]"), ptrFiles
[i
]->cFileName
);
1376 _stprintf(szTempFname
, _T("%s"), ptrFiles
[i
]->cFileName
);
1379 ConOutPrintfPaging(FALSE
,_T("%-*s"), iLongestName
+ 1, szTempFname
);
1381 ConOutPrintf(_T("%-*s"), iLongestName
+ 1, szTempFname
);
1384 * We print a new line at the end of each column
1385 * except for the case that it is the last item.
1387 if (!((i
+ 1) % iColumns
) && (i
< (dwCount
- 1)))
1390 ConOutPrintfPaging(FALSE
,_T("\n"));
1392 ConOutPrintf(_T("\n"));
1396 /* Add a new line after the last item */
1398 ConOutPrintfPaging(FALSE
,_T("\n"));
1400 ConOutPrintf(_T("\n"));
1408 * The function that prints in old style
1411 DirPrintOldList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1412 DWORD dwCount
, /* [IN] The quantity of files */
1413 TCHAR
* szCurPath
, /* [IN] Full path of current directory */
1414 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1416 DWORD i
; /* An indexer for "for"s */
1417 TCHAR szName
[10]; /* The name of file */
1418 TCHAR szExt
[5]; /* The extension of file */
1419 TCHAR szDate
[30],szTime
[30]; /* Used to format time and date */
1420 TCHAR szSize
[30]; /* The size of file */
1421 int iSizeFormat
; /* The format of size field */
1422 ULARGE_INTEGER u64FileSize
; /* The file size */
1424 for(i
= 0;i
< dwCount
;i
++)
1426 /* Broke 8.3 format */
1427 if (*ptrFiles
[i
]->cAlternateFileName
)
1429 /* If the file is long named then we read the alter name */
1430 getName( ptrFiles
[i
]->cAlternateFileName
, szName
);
1431 _tcscpy(szExt
, getExt( ptrFiles
[i
]->cAlternateFileName
));
1435 /* If the file is not long name we read its original name */
1436 getName( ptrFiles
[i
]->cFileName
, szName
);
1437 _tcscpy(szExt
, getExt( ptrFiles
[i
]->cFileName
));
1440 /* Calculate size */
1441 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1443 /* Directory, no size it's a directory*/
1445 _tcscpy(szSize
, _T("<DIR>"));
1451 u64FileSize
.HighPart
= ptrFiles
[i
]->nFileSizeHigh
;
1452 u64FileSize
.LowPart
= ptrFiles
[i
]->nFileSizeLow
;
1453 ConvertULargeInteger(u64FileSize
, szSize
, 20, lpFlags
->bTSeperator
);
1456 /* Format date and time */
1457 DirPrintFileDateTime(szDate
,szTime
,ptrFiles
[i
],lpFlags
);
1459 /* Print the line */
1461 ConOutPrintfPaging(FALSE
,_T("%-8s %-3s %*s %s %s\n"),
1462 szName
, /* The file's 8.3 name */
1463 szExt
, /* The file's 8.3 extension */
1464 iSizeFormat
, /* print format for size column */
1465 szSize
, /* The size of file or "<DIR>" for dirs */
1466 szDate
, /* The date of file/dir */
1467 szTime
); /* The time of file/dir */
1469 ConOutPrintf(_T("%-8s %-3s %*s %s %s\n"),
1470 szName
, /* The file's 8.3 name */
1471 szExt
, /* The file's 8.3 extension */
1472 iSizeFormat
, /* print format for size column */
1473 szSize
, /* The size of file or "<DIR>" for dirs */
1474 szDate
, /* The date of file/dir */
1475 szTime
); /* The time of file/dir */
1482 * The function that prints in bare format
1485 DirPrintBareList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1486 DWORD dwCount
, /* [IN] The number of files */
1487 LPTSTR lpCurPath
, /* [IN] Full path of current directory */
1488 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1490 TCHAR szFullName
[MAX_PATH
];
1493 for (i
= 0; i
< dwCount
; i
++)
1495 if ((_tcscmp(ptrFiles
[i
]->cFileName
, _T(".")) == 0) ||
1496 (_tcscmp(ptrFiles
[i
]->cFileName
, _T("..")) == 0))
1498 /* at bare format we don't print "." and ".." folder */
1501 if (lpFlags
->bRecursive
)
1503 /* at recursive mode we print full path of file */
1504 _tcscpy(szFullName
, lpCurPath
);
1505 _tcscat(szFullName
, ptrFiles
[i
]->cFileName
);
1507 ConOutPrintfPaging(FALSE
,_T("%s\n"), szFullName
);
1509 ConOutPrintf(_T("%s\n"), szFullName
);
1513 /* if we are not in recursive mode we print the file names */
1515 ConOutPrintfPaging(FALSE
,_T("%s\n"),ptrFiles
[i
]->cFileName
);
1517 ConOutPrintf(_T("%s\n"),ptrFiles
[i
]->cFileName
);
1526 * The functions that prints the files list
1529 DirPrintFiles(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1530 DWORD dwCount
, /* [IN] The quantity of files */
1531 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1532 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1534 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1535 TCHAR szTemp
[MAX_PATH
]; /* A buffer to format the directory header */
1537 /* Print directory header */
1538 _tcscpy(szTemp
, szCurPath
);
1540 /* We cut the trailing \ of the full path */
1541 szTemp
[_tcslen(szTemp
)-1] = _T('\0');
1543 /* Condition to print header:
1544 We are not printing in bare format
1545 and if we are in recursive mode... we must have results */
1546 if (!(lpFlags
->bBareFormat
) && !((lpFlags
->bRecursive
) && (dwCount
<= 0)))
1548 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP7
, szMsg
, RC_STRING_MAX_SIZE
);
1550 ConOutPrintfPaging(FALSE
,szMsg
, szTemp
);
1552 ConOutPrintf(szMsg
, szTemp
);
1555 if (lpFlags
->bBareFormat
)
1558 DirPrintBareList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1560 else if(lpFlags
->bShortName
)
1562 /* New list style / Short names */
1563 DirPrintNewList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1565 else if(lpFlags
->bWideListColSort
|| lpFlags
->bWideList
)
1568 DirPrintWideList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1570 else if (lpFlags
->bNewLongList
)
1573 DirPrintNewList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1577 /* If nothing is selected old list is the default */
1578 DirPrintOldList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1587 * Compares 2 files based on the order criteria
1590 CompareFiles(LPWIN32_FIND_DATA lpFile1
, /* [IN] A pointer to WIN32_FIND_DATA of file 1 */
1591 LPWIN32_FIND_DATA lpFile2
, /* [IN] A pointer to WIN32_FIND_DATA of file 2 */
1592 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags that we use to list */
1594 ULARGE_INTEGER u64File1
;
1595 ULARGE_INTEGER u64File2
;
1597 long iComp
= 0; /* The comparison result */
1599 /* Calculate critiries by order given from user */
1600 for (i
= 0;i
< lpFlags
->stOrderBy
.sCriteriaCount
;i
++)
1603 /* Calculate criteria */
1604 switch(lpFlags
->stOrderBy
.eCriteria
[i
])
1606 case ORDER_SIZE
: /* Order by size /o:s */
1607 /* concat the 32bit integers to a 64bit */
1608 u64File1
.LowPart
= lpFile1
->nFileSizeLow
;
1609 u64File1
.HighPart
= lpFile1
->nFileSizeHigh
;
1610 u64File2
.LowPart
= lpFile2
->nFileSizeLow
;
1611 u64File2
.HighPart
= lpFile2
->nFileSizeHigh
;
1613 /* In case that differnce is too big for a long */
1614 if (u64File1
.QuadPart
< u64File2
.QuadPart
)
1616 else if (u64File1
.QuadPart
> u64File2
.QuadPart
)
1622 case ORDER_DIRECTORY
: /* Order by directory attribute /o:g */
1623 iComp
= ((lpFile2
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)-
1624 (lpFile1
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
));
1627 case ORDER_EXTENSION
: /* Order by extension name /o:e */
1628 iComp
= _tcsicmp(getExt(lpFile1
->cFileName
),getExt(lpFile2
->cFileName
));
1631 case ORDER_NAME
: /* Order by filename /o:n */
1632 iComp
= _tcsicmp(lpFile1
->cFileName
, lpFile2
->cFileName
);
1635 case ORDER_TIME
: /* Order by file's time /o:t */
1636 /* We compare files based on the time field selected by /t */
1637 switch(lpFlags
->stTimeField
.eTimeField
)
1639 case TF_CREATIONDATE
:
1640 /* concat the 32bit integers to a 64bit */
1641 u64File1
.LowPart
= lpFile1
->ftCreationTime
.dwLowDateTime
;
1642 u64File1
.HighPart
= lpFile1
->ftCreationTime
.dwHighDateTime
;
1643 u64File2
.LowPart
= lpFile2
->ftCreationTime
.dwLowDateTime
;
1644 u64File2
.HighPart
= lpFile2
->ftCreationTime
.dwHighDateTime
;
1646 case TF_LASTACCESSEDDATE
:
1647 /* concat the 32bit integers to a 64bit */
1648 u64File1
.LowPart
= lpFile1
->ftLastAccessTime
.dwLowDateTime
;
1649 u64File1
.HighPart
= lpFile1
->ftLastAccessTime
.dwHighDateTime
;
1650 u64File2
.LowPart
= lpFile2
->ftLastAccessTime
.dwLowDateTime
;
1651 u64File2
.HighPart
= lpFile2
->ftLastAccessTime
.dwHighDateTime
;
1653 case TF_MODIFIEDDATE
:
1654 /* concat the 32bit integers to a 64bit */
1655 u64File1
.LowPart
= lpFile1
->ftLastWriteTime
.dwLowDateTime
;
1656 u64File1
.HighPart
= lpFile1
->ftLastWriteTime
.dwHighDateTime
;
1657 u64File2
.LowPart
= lpFile2
->ftLastWriteTime
.dwLowDateTime
;
1658 u64File2
.HighPart
= lpFile2
->ftLastWriteTime
.dwHighDateTime
;
1662 /* In case that differnce is too big for a long */
1663 if (u64File1
.QuadPart
< u64File2
.QuadPart
)
1665 else if (u64File1
.QuadPart
> u64File2
.QuadPart
)
1672 /* Reverse if desired */
1673 if (lpFlags
->stOrderBy
.bCriteriaRev
[i
])
1676 /* If that criteria was enough for distinguishing
1677 the files/dirs,there is no need to calculate the others*/
1678 if (iComp
!= 0) break;
1681 /* Translate the value of iComp to boolean */
1691 * Sort files by the order criterias using quicksort method
1694 QsortFiles(LPWIN32_FIND_DATA ptrArray
[], /* [IN/OUT] The array with file info pointers */
1695 int i
, /* [IN] The index of first item in array */
1696 int j
, /* [IN] The index to last item in array */
1697 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags that we will use to sort */
1699 LPWIN32_FIND_DATA lpTemp
; /* A temporary pointer */
1700 int First
, Last
, Temp
;
1710 if (Way
== CompareFiles(ptrArray
[i
], ptrArray
[j
], lpFlags
))
1712 /* Swap the pointers of the array */
1713 lpTemp
= ptrArray
[i
];
1714 ptrArray
[i
]= ptrArray
[j
];
1715 ptrArray
[j
] = lpTemp
;
1717 /* Swap the indexes for inverting sorting */
1728 QsortFiles(ptrArray
,First
, i
-1, lpFlags
);
1729 QsortFiles(ptrArray
,i
+1,Last
, lpFlags
);
1738 * The functions that does everything except for printing results
1741 DirList(LPTSTR szPath
, /* [IN] The path that dir starts */
1742 LPTSTR szFilespec
, /* [IN] The type of file that we are looking for */
1743 LPINT pLine
, /* FIXME: Maybe used for paginating */
1744 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags of the listing */
1746 HANDLE hSearch
; /* The handle of the search */
1747 HANDLE hRecSearch
; /* The handle for searching recursivly */
1748 WIN32_FIND_DATA wfdFileInfo
; /* The info of file that found */
1749 LPWIN32_FIND_DATA
* ptrFileArray
; /* An array of pointers with all the files */
1750 PDIRFINDLISTNODE ptrStartNode
; /* The pointer to the first node */
1751 PDIRFINDLISTNODE ptrNextNode
; /* A pointer used for relatives refernces */
1752 TCHAR szFullPath
[MAX_PATH
]; /* The full path that we are listing with trailing \ */
1753 TCHAR szFullFileSpec
[MAX_PATH
]; /* The full path with file specs that we ll request\ */
1754 DWORD dwCount
; /* A counter of files found in directory */
1755 DWORD dwCountFiles
; /* Counter for files */
1756 DWORD dwCountDirs
; /* Counter for directories */
1757 ULARGE_INTEGER u64CountBytes
; /* Counter for bytes */
1758 ULARGE_INTEGER u64Temp
; /* A temporary counter */
1760 /* Initialize Variables */
1761 ptrStartNode
= NULL
;
1766 u64CountBytes
.QuadPart
= 0;
1768 /* Create szFullPath and szFullFileSpec */
1769 _tcscpy (szFullPath
, szPath
);
1770 if (szFullPath
[_tcslen(szFullPath
) - 1] != _T('\\'))
1771 _tcscat (szFullPath
, _T("\\"));
1772 _tcscpy (szFullFileSpec
, szFullPath
);
1773 _tcscat (szFullFileSpec
, szFilespec
);
1775 /* Prepare the linked list, first node is allocated */
1776 ptrStartNode
= malloc(sizeof(DIRFINDLISTNODE
));
1777 if (ptrStartNode
== NULL
)
1780 ConErrPrintf(_T("DEBUG: Cannot allocate memory for ptrStartNode!\n"));
1782 return 1; /* Error cannot allocate memory for 1st object */
1784 ptrNextNode
= ptrStartNode
;
1786 /* Collect the results for the current folder */
1787 hSearch
= FindFirstFile(szFullFileSpec
, &wfdFileInfo
);
1790 if (hSearch
!= INVALID_HANDLE_VALUE
)
1792 /* Here we filter all the specified attributes */
1793 if ((wfdFileInfo
.dwFileAttributes
& lpFlags
->stAttribs
.dwAttribMask
)
1794 == (lpFlags
->stAttribs
.dwAttribMask
& lpFlags
->stAttribs
.dwAttribVal
))
1796 ptrNextNode
->ptrNext
= malloc(sizeof(DIRFINDLISTNODE
));
1797 if (ptrNextNode
->ptrNext
== NULL
)
1800 ConErrPrintf(_T("DEBUG: Cannot allocate memory for ptrNextNode->ptrNext!\n"));
1802 while (ptrStartNode
)
1804 ptrNextNode
= ptrStartNode
->ptrNext
;
1806 ptrStartNode
= ptrNextNode
;
1812 /* If malloc fails we go to next file in hope it works,
1813 without braking the linked list! */
1814 if (ptrNextNode
->ptrNext
)
1816 /* Copy the info of search at linked list */
1817 memcpy(&ptrNextNode
->ptrNext
->stFindInfo
,
1819 sizeof(WIN32_FIND_DATA
));
1821 /* If lower case is selected do it here */
1822 if (lpFlags
->bLowerCase
)
1824 _tcslwr(ptrNextNode
->ptrNext
->stFindInfo
.cAlternateFileName
);
1825 _tcslwr(ptrNextNode
->ptrNext
->stFindInfo
.cFileName
);
1828 /* Continue at next node at linked list */
1829 ptrNextNode
= ptrNextNode
->ptrNext
;
1832 /* Grab statistics */
1833 if (wfdFileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1842 u64Temp
.HighPart
= wfdFileInfo
.nFileSizeHigh
;
1843 u64Temp
.LowPart
= wfdFileInfo
.nFileSizeLow
;
1844 u64CountBytes
.QuadPart
+= u64Temp
.QuadPart
;
1849 }while(FindNextFile(hSearch
, &wfdFileInfo
));
1852 /* Terminate list */
1853 ptrNextNode
->ptrNext
= NULL
;
1855 /* Calculate and allocate space need for making an array of pointers */
1856 ptrFileArray
= malloc(sizeof(LPWIN32_FIND_DATA
) * dwCount
);
1857 if (ptrFileArray
== NULL
)
1860 ConErrPrintf(_T("DEBUG: Cannot allocate memory for ptrFileArray!\n"));
1862 while (ptrStartNode
)
1864 ptrNextNode
= ptrStartNode
->ptrNext
;
1866 ptrStartNode
= ptrNextNode
;
1873 * Create an array of pointers from the linked list
1874 * this will be used to sort and print data, rather than the list
1876 ptrNextNode
= ptrStartNode
;
1878 while (ptrNextNode
->ptrNext
)
1880 *(ptrFileArray
+ dwCount
) = &ptrNextNode
->ptrNext
->stFindInfo
;
1881 ptrNextNode
= ptrNextNode
->ptrNext
;
1885 /* Sort Data if requested*/
1886 if (lpFlags
->stOrderBy
.sCriteriaCount
> 0)
1887 QsortFiles(ptrFileArray
, 0, dwCount
-1,lpFlags
);
1890 DirPrintFiles(ptrFileArray
, dwCount
, szFullPath
, lpFlags
);
1895 /* Add statistics to recursive statistics*/
1896 recurse_dir_cnt
+= dwCountDirs
;
1897 recurse_file_cnt
+= dwCountFiles
;
1898 recurse_bytes
.QuadPart
+= u64CountBytes
.QuadPart
;
1900 /* Do the recursive job if requested
1901 the recursive is be done on ALL(indepent of their attribs)
1902 directoried of the current one.*/
1903 if (lpFlags
->bRecursive
)
1905 /* The new search is involving any *.* file */
1906 _tcscpy(szFullFileSpec
, szFullPath
);
1907 _tcscat(szFullFileSpec
, _T("*.*"));
1908 hRecSearch
= FindFirstFile (szFullFileSpec
, &wfdFileInfo
);
1911 if (hRecSearch
!= INVALID_HANDLE_VALUE
)
1913 /* We search for directories other than "." and ".." */
1914 if ((_tcsicmp(wfdFileInfo
.cFileName
, _T(".")) != 0) &&
1915 (_tcsicmp(wfdFileInfo
.cFileName
, _T("..")) != 0 ) &&
1916 (wfdFileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
))
1918 /* Concat the path and the directory to do recursive */
1919 _tcscpy(szFullFileSpec
, szFullPath
);
1920 _tcscat(szFullFileSpec
, wfdFileInfo
.cFileName
);
1921 /* We do the same for tha folder */
1922 DirList(szFullFileSpec
, szFilespec
, pLine
,lpFlags
);
1925 }while(FindNextFile(hRecSearch
,&wfdFileInfo
));
1926 FindClose(hRecSearch
);
1929 /* Free linked list */
1930 while (ptrStartNode
)
1932 ptrNextNode
= ptrStartNode
->ptrNext
;
1934 ptrStartNode
= ptrNextNode
;
1946 * internal dir command
1949 CommandDir(LPTSTR first
, LPTSTR rest
)
1951 TCHAR dircmd
[256]; /* A variable to store the DIRCMD enviroment variable */
1953 TCHAR szPath
[MAX_PATH
];
1954 TCHAR szFilespec
[MAX_PATH
];
1959 DIRSWITCHFLAGS stFlags
;
1961 /* Initialize variables */
1963 recurse_dir_cnt
= 0L;
1964 recurse_file_cnt
= 0L;
1965 recurse_bytes
.QuadPart
= 0;
1967 /* Initialize Switch Flags < Default switches are setted here!> */
1968 stFlags
.b4Digit
= TRUE
;
1969 stFlags
.bBareFormat
= FALSE
;
1970 stFlags
.bLowerCase
= FALSE
;
1971 stFlags
.bNewLongList
= TRUE
;
1972 stFlags
.bPause
= FALSE
;
1973 stFlags
.bRecursive
= FALSE
;
1974 stFlags
.bShortName
= FALSE
;
1975 stFlags
.bTSeperator
= TRUE
;
1976 stFlags
.bUser
= FALSE
;
1977 stFlags
.bWideList
= FALSE
;
1978 stFlags
.bWideListColSort
= FALSE
;
1979 stFlags
.stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
1980 stFlags
.stTimeField
.bUnSet
= FALSE
;
1981 stFlags
.stAttribs
.dwAttribMask
= FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_SYSTEM
;
1982 stFlags
.stAttribs
.dwAttribVal
= 0L;
1983 stFlags
.stAttribs
.bUnSet
= FALSE
;
1984 stFlags
.stOrderBy
.sCriteriaCount
= 0;
1985 stFlags
.stOrderBy
.bUnSet
= FALSE
;
1989 /* read the parameters from the DIRCMD environment variable */
1990 if (GetEnvironmentVariable (_T("DIRCMD"), dircmd
, 256))
1991 if (!DirReadParam(dircmd
, ¶ms
, &entries
, &stFlags
))
1997 /* read the parameters */
1998 if (!DirReadParam(rest
, ¶ms
, &entries
, &stFlags
) || CheckCtrlBreak(BREAK_INPUT
))
2004 /* default to current directory */
2006 if(!add_entry(&entries
, ¶ms
, _T("."))) {
2012 for(loop
= 0; loop
< entries
; loop
++)
2014 /* parse the directory info */
2015 if (DirParsePathspec (params
[loop
], szPath
, szFilespec
) || CheckCtrlBreak(BREAK_INPUT
))
2022 Uncomment this to show the final state of switch flags*/
2026 ConOutPrintf(_T("Attributes mask/value %x/%x\n"),stFlags
.stAttribs
.dwAttribMask
,stFlags
.stAttribs
.dwAttribVal
);
2027 ConOutPrintf(_T("(B) Bare format : %i\n"), stFlags
.bBareFormat
);
2028 ConOutPrintf(_T("(C) Thousand : %i\n"), stFlags
.bTSeperator
);
2029 ConOutPrintf(_T("(W) Wide list : %i\n"), stFlags
.bWideList
);
2030 ConOutPrintf(_T("(D) Wide list sort by column : %i\n"), stFlags
.bWideListColSort
);
2031 ConOutPrintf(_T("(L) Lowercase : %i\n"), stFlags
.bLowerCase
);
2032 ConOutPrintf(_T("(N) New : %i\n"), stFlags
.bNewLongList
);
2033 ConOutPrintf(_T("(O) Order : %i\n"), stFlags
.stOrderBy
.sCriteriaCount
);
2034 for (i
=0;i
<stFlags
.stOrderBy
.sCriteriaCount
;i
++)
2035 ConOutPrintf(_T(" Order Criteria [%i]: %i (Reversed: %i)\n"),i
, stFlags
.stOrderBy
.eCriteria
[i
], stFlags
.stOrderBy
.bCriteriaRev
[i
] );
2036 ConOutPrintf(_T("(P) Pause : %i\n"), stFlags
.bPause
);
2037 ConOutPrintf(_T("(Q) Owner : %i\n"), stFlags
.bUser
);
2038 ConOutPrintf(_T("(S) Recursive : %i\n"), stFlags
.bRecursive
);
2039 ConOutPrintf(_T("(T) Time field : %i\n"), stFlags
.stTimeField
.eTimeField
);
2040 ConOutPrintf(_T("(X) Short names : %i\n"), stFlags
.bShortName
);
2041 ConOutPrintf(_T("Parameter : %s\n"), params
[loop
] );
2045 /* Print the drive header if the drive changed */
2046 if(cDrive
!= szPath
[0] && !stFlags
.bBareFormat
) {
2047 if (!PrintDirectoryHeader (szPath
, &nLine
, &stFlags
)) {
2056 /* do the actual dir */
2057 if (DirList (szPath
, szFilespec
, &nLine
, &stFlags
))
2064 /* print the footer */
2065 PrintSummary(szPath
,