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();
1134 /* In bare format we don't print results */
1135 if (lpFlags
->bBareFormat
)
1138 /* Print recursive specific results */
1140 /* Take this code offline to fix /S does not print duoble info */
1141 if (lpFlags
->bRecursive
)
1143 ConvertULargeInteger(u64Bytes
, szBuffer
, sizeof(szBuffer
), lpFlags
->bTSeperator
);
1144 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP5
, szMsg
, RC_STRING_MAX_SIZE
);
1146 ConOutPrintfPaging(FALSE
,szMsg
,ulFiles
, szBuffer
);
1148 ConOutPrintf(szMsg
,ulFiles
, szBuffer
);
1153 /* Print File Summary */
1154 /* Condition to print summary is:
1155 If we are not in bare format and if we have results! */
1158 ConvertULargeInteger(u64Bytes
, szBuffer
, 20, lpFlags
->bTSeperator
);
1159 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP8
, szMsg
, RC_STRING_MAX_SIZE
);
1161 ConOutPrintfPaging(FALSE
,szMsg
,ulFiles
, szBuffer
);
1163 ConOutPrintf(szMsg
,ulFiles
, szBuffer
);
1168 /* Print total directories and freespace */
1169 szRoot
[0] = szPath
[0];
1170 GetUserDiskFreeSpace(szRoot
, &uliFree
);
1171 ConvertULargeInteger(uliFree
, szBuffer
, sizeof(szBuffer
), lpFlags
->bTSeperator
);
1172 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP6
, (LPTSTR
) szMsg
, RC_STRING_MAX_SIZE
);
1174 ConOutPrintfPaging(FALSE
,szMsg
,ulDirs
, szBuffer
);
1176 ConOutPrintf(szMsg
,ulDirs
, szBuffer
);
1184 * Get the extension of a filename
1186 TCHAR
* getExt(const TCHAR
* file
)
1188 static TCHAR
*NoExt
= _T("");
1189 TCHAR
* lastdot
= _tcsrchr(file
, _T('.'));
1190 return (lastdot
!= NULL
? lastdot
+ 1 : NoExt
);
1196 * Get the name of the file without extension
1199 getName(const TCHAR
* file
, TCHAR
* dest
)
1204 /* Check for "." and ".." folders */
1205 if ((_tcscmp(file
, _T(".")) == 0) ||
1206 (_tcscmp(file
, _T("..")) == 0))
1212 end
= _tcsrchr(file
, _T('.'));
1214 iLen
= _tcslen(file
);
1216 iLen
= (end
- file
);
1219 _tcsncpy(dest
, file
, iLen
);
1220 *(dest
+ iLen
) = _T('\0');
1229 * The function that prints in new style
1232 DirPrintNewList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN]Files' Info */
1233 DWORD dwCount
, /* [IN] The quantity of files */
1234 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1235 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1239 TCHAR szShortName
[15];
1243 ULARGE_INTEGER u64FileSize
;
1245 for (i
= 0;i
< dwCount
;i
++)
1247 /* Calculate size */
1248 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1252 _tcscpy(szSize
, _T("<DIR>"));
1258 u64FileSize
.HighPart
= ptrFiles
[i
]->nFileSizeHigh
;
1259 u64FileSize
.LowPart
= ptrFiles
[i
]->nFileSizeLow
;
1260 ConvertULargeInteger(u64FileSize
, szSize
, 20, lpFlags
->bTSeperator
);
1263 /* Calculate short name */
1264 szShortName
[0] = _T('\0');
1265 if (lpFlags
->bShortName
)
1266 _stprintf(szShortName
, _T(" %-12s"), ptrFiles
[i
]->cAlternateFileName
);
1268 /* Format date and time */
1269 DirPrintFileDateTime(szDate
, szTime
, ptrFiles
[i
], lpFlags
);
1271 /* Print the line */
1274 if (ConOutPrintfPaging(FALSE
,_T("%10s %-8s %*s%s %s\n"),
1280 ptrFiles
[i
]->cFileName
) == 1)
1284 ConOutPrintf(_T("%10s %-8s %*s%s %s\n"),
1290 ptrFiles
[i
]->cFileName
);
1298 * The function that prints in wide list
1301 DirPrintWideList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1302 DWORD dwCount
, /* [IN] The quantity of files */
1303 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1304 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1310 TCHAR szTempFname
[MAX_PATH
];
1315 /* Calculate longest name */
1317 for (i
= 0; i
< dwCount
; i
++)
1319 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1321 /* Directories need 2 additinal characters for brackets */
1322 if ((_tcslen(ptrFiles
[i
]->cFileName
) + 2) > iLongestName
)
1323 iLongestName
= _tcslen(ptrFiles
[i
]->cFileName
) + 2;
1327 if (_tcslen(ptrFiles
[i
]->cFileName
) > iLongestName
)
1328 iLongestName
= _tcslen(ptrFiles
[i
]->cFileName
);
1332 /* Count the highest number of columns */
1333 GetScreenSize(&iScreenWidth
, 0);
1334 iColumns
= iScreenWidth
/ iLongestName
;
1336 /* Check if there is enough space for spaces between names */
1337 if (((iLongestName
* iColumns
) + iColumns
) >= (UINT
)iScreenWidth
)
1340 /* A last check at iColumns to avoid division by zero */
1344 /* Print Column sorted */
1345 if (lpFlags
->bWideListColSort
)
1347 /* Calculate the lines that will be printed */
1348 // iLines = ceil((float)dwCount/(float)iColumns);
1349 iLines
= (USHORT
)(dwCount
/ iColumns
);
1351 for (i
= 0;i
< iLines
;i
++)
1353 for (j
= 0; j
< iColumns
; j
++)
1355 temp
= (j
* iLines
) + i
;
1356 if (temp
>= dwCount
)
1359 if (ptrFiles
[temp
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1360 _stprintf(szTempFname
, _T("[%s]"), ptrFiles
[temp
]->cFileName
);
1362 _stprintf(szTempFname
, _T("%s"), ptrFiles
[temp
]->cFileName
);
1365 ConOutPrintfPaging(FALSE
,_T("%-*s"), iLongestName
+ 1 , szTempFname
);
1367 ConOutPrintf(_T("%-*s"), iLongestName
+ 1 , szTempFname
);
1371 ConOutPrintfPaging(FALSE
,_T("\n"));
1373 ConOutPrintf(_T("\n"));
1378 /* Print Line sorted */
1379 for (i
= 0; i
< dwCount
; i
++)
1381 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1382 _stprintf(szTempFname
, _T("[%s]"), ptrFiles
[i
]->cFileName
);
1384 _stprintf(szTempFname
, _T("%s"), ptrFiles
[i
]->cFileName
);
1387 ConOutPrintfPaging(FALSE
,_T("%-*s"), iLongestName
+ 1, szTempFname
);
1389 ConOutPrintf(_T("%-*s"), iLongestName
+ 1, szTempFname
);
1392 * We print a new line at the end of each column
1393 * except for the case that it is the last item.
1395 if (!((i
+ 1) % iColumns
) && (i
< (dwCount
- 1)))
1398 ConOutPrintfPaging(FALSE
,_T("\n"));
1400 ConOutPrintf(_T("\n"));
1404 /* Add a new line after the last item */
1406 ConOutPrintfPaging(FALSE
,_T("\n"));
1408 ConOutPrintf(_T("\n"));
1416 * The function that prints in old style
1419 DirPrintOldList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1420 DWORD dwCount
, /* [IN] The quantity of files */
1421 TCHAR
* szCurPath
, /* [IN] Full path of current directory */
1422 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1424 DWORD i
; /* An indexer for "for"s */
1425 TCHAR szName
[10]; /* The name of file */
1426 TCHAR szExt
[5]; /* The extension of file */
1427 TCHAR szDate
[30],szTime
[30]; /* Used to format time and date */
1428 TCHAR szSize
[30]; /* The size of file */
1429 int iSizeFormat
; /* The format of size field */
1430 ULARGE_INTEGER u64FileSize
; /* The file size */
1432 for(i
= 0;i
< dwCount
;i
++)
1434 /* Broke 8.3 format */
1435 if (*ptrFiles
[i
]->cAlternateFileName
)
1437 /* If the file is long named then we read the alter name */
1438 getName( ptrFiles
[i
]->cAlternateFileName
, szName
);
1439 _tcscpy(szExt
, getExt( ptrFiles
[i
]->cAlternateFileName
));
1443 /* If the file is not long name we read its original name */
1444 getName( ptrFiles
[i
]->cFileName
, szName
);
1445 _tcscpy(szExt
, getExt( ptrFiles
[i
]->cFileName
));
1448 /* Calculate size */
1449 if (ptrFiles
[i
]->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1451 /* Directory, no size it's a directory*/
1453 _tcscpy(szSize
, _T("<DIR>"));
1459 u64FileSize
.HighPart
= ptrFiles
[i
]->nFileSizeHigh
;
1460 u64FileSize
.LowPart
= ptrFiles
[i
]->nFileSizeLow
;
1461 ConvertULargeInteger(u64FileSize
, szSize
, 20, lpFlags
->bTSeperator
);
1464 /* Format date and time */
1465 DirPrintFileDateTime(szDate
,szTime
,ptrFiles
[i
],lpFlags
);
1467 /* Print the line */
1470 if (ConOutPrintfPaging(FALSE
,_T("%-8s %-3s %*s %s %s\n"),
1471 szName
, /* The file's 8.3 name */
1472 szExt
, /* The file's 8.3 extension */
1473 iSizeFormat
, /* print format for size column */
1474 szSize
, /* The size of file or "<DIR>" for dirs */
1475 szDate
, /* The date of file/dir */
1476 szTime
) == 1) /* The time of file/dir */
1482 ConOutPrintf(_T("%-8s %-3s %*s %s %s\n"),
1483 szName
, /* The file's 8.3 name */
1484 szExt
, /* The file's 8.3 extension */
1485 iSizeFormat
, /* print format for size column */
1486 szSize
, /* The size of file or "<DIR>" for dirs */
1487 szDate
, /* The date of file/dir */
1488 szTime
); /* The time of file/dir */
1495 * The function that prints in bare format
1498 DirPrintBareList(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1499 DWORD dwCount
, /* [IN] The number of files */
1500 LPTSTR lpCurPath
, /* [IN] Full path of current directory */
1501 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1503 TCHAR szFullName
[MAX_PATH
];
1506 for (i
= 0; i
< dwCount
; i
++)
1508 if ((_tcscmp(ptrFiles
[i
]->cFileName
, _T(".")) == 0) ||
1509 (_tcscmp(ptrFiles
[i
]->cFileName
, _T("..")) == 0))
1511 /* at bare format we don't print "." and ".." folder */
1514 if (lpFlags
->bRecursive
)
1516 /* at recursive mode we print full path of file */
1517 _tcscpy(szFullName
, lpCurPath
);
1518 _tcscat(szFullName
, ptrFiles
[i
]->cFileName
);
1521 if (ConOutPrintfPaging(FALSE
,_T("%s\n"), szFullName
) == 1)
1527 ConOutPrintf(_T("%s\n"), szFullName
);
1531 /* if we are not in recursive mode we print the file names */
1534 if (ConOutPrintfPaging(FALSE
,_T("%s\n"),ptrFiles
[i
]->cFileName
) == 1)
1540 ConOutPrintf(_T("%s\n"),ptrFiles
[i
]->cFileName
);
1549 * The functions that prints the files list
1552 DirPrintFiles(LPWIN32_FIND_DATA ptrFiles
[], /* [IN] Files' Info */
1553 DWORD dwCount
, /* [IN] The quantity of files */
1554 TCHAR
*szCurPath
, /* [IN] Full path of current directory */
1555 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags used */
1557 TCHAR szMsg
[RC_STRING_MAX_SIZE
];
1558 TCHAR szTemp
[MAX_PATH
]; /* A buffer to format the directory header */
1560 /* Print directory header */
1561 _tcscpy(szTemp
, szCurPath
);
1563 /* We cut the trailing \ of the full path */
1564 szTemp
[_tcslen(szTemp
)-1] = _T('\0');
1566 /* Condition to print header:
1567 We are not printing in bare format
1568 and if we are in recursive mode... we must have results */
1569 if (!(lpFlags
->bBareFormat
) && !((lpFlags
->bRecursive
) && (dwCount
<= 0)))
1571 LoadString(CMD_ModuleHandle
, STRING_DIR_HELP7
, szMsg
, RC_STRING_MAX_SIZE
);
1574 if (ConOutPrintfPaging(FALSE
,szMsg
, szTemp
) == 1)
1580 ConOutPrintf(szMsg
, szTemp
);
1583 if (lpFlags
->bBareFormat
)
1586 DirPrintBareList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1588 else if(lpFlags
->bShortName
)
1590 /* New list style / Short names */
1591 DirPrintNewList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1593 else if(lpFlags
->bWideListColSort
|| lpFlags
->bWideList
)
1596 DirPrintWideList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1598 else if (lpFlags
->bNewLongList
)
1601 DirPrintNewList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1605 /* If nothing is selected old list is the default */
1606 DirPrintOldList(ptrFiles
, dwCount
, szCurPath
, lpFlags
);
1615 * Compares 2 files based on the order criteria
1618 CompareFiles(LPWIN32_FIND_DATA lpFile1
, /* [IN] A pointer to WIN32_FIND_DATA of file 1 */
1619 LPWIN32_FIND_DATA lpFile2
, /* [IN] A pointer to WIN32_FIND_DATA of file 2 */
1620 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags that we use to list */
1622 ULARGE_INTEGER u64File1
;
1623 ULARGE_INTEGER u64File2
;
1625 long iComp
= 0; /* The comparison result */
1627 /* Calculate critiries by order given from user */
1628 for (i
= 0;i
< lpFlags
->stOrderBy
.sCriteriaCount
;i
++)
1631 /* Calculate criteria */
1632 switch(lpFlags
->stOrderBy
.eCriteria
[i
])
1634 case ORDER_SIZE
: /* Order by size /o:s */
1635 /* concat the 32bit integers to a 64bit */
1636 u64File1
.LowPart
= lpFile1
->nFileSizeLow
;
1637 u64File1
.HighPart
= lpFile1
->nFileSizeHigh
;
1638 u64File2
.LowPart
= lpFile2
->nFileSizeLow
;
1639 u64File2
.HighPart
= lpFile2
->nFileSizeHigh
;
1641 /* In case that differnce is too big for a long */
1642 if (u64File1
.QuadPart
< u64File2
.QuadPart
)
1644 else if (u64File1
.QuadPart
> u64File2
.QuadPart
)
1650 case ORDER_DIRECTORY
: /* Order by directory attribute /o:g */
1651 iComp
= ((lpFile2
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)-
1652 (lpFile1
->dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
));
1655 case ORDER_EXTENSION
: /* Order by extension name /o:e */
1656 iComp
= _tcsicmp(getExt(lpFile1
->cFileName
),getExt(lpFile2
->cFileName
));
1659 case ORDER_NAME
: /* Order by filename /o:n */
1660 iComp
= _tcsicmp(lpFile1
->cFileName
, lpFile2
->cFileName
);
1663 case ORDER_TIME
: /* Order by file's time /o:t */
1664 /* We compare files based on the time field selected by /t */
1665 switch(lpFlags
->stTimeField
.eTimeField
)
1667 case TF_CREATIONDATE
:
1668 /* concat the 32bit integers to a 64bit */
1669 u64File1
.LowPart
= lpFile1
->ftCreationTime
.dwLowDateTime
;
1670 u64File1
.HighPart
= lpFile1
->ftCreationTime
.dwHighDateTime
;
1671 u64File2
.LowPart
= lpFile2
->ftCreationTime
.dwLowDateTime
;
1672 u64File2
.HighPart
= lpFile2
->ftCreationTime
.dwHighDateTime
;
1674 case TF_LASTACCESSEDDATE
:
1675 /* concat the 32bit integers to a 64bit */
1676 u64File1
.LowPart
= lpFile1
->ftLastAccessTime
.dwLowDateTime
;
1677 u64File1
.HighPart
= lpFile1
->ftLastAccessTime
.dwHighDateTime
;
1678 u64File2
.LowPart
= lpFile2
->ftLastAccessTime
.dwLowDateTime
;
1679 u64File2
.HighPart
= lpFile2
->ftLastAccessTime
.dwHighDateTime
;
1681 case TF_MODIFIEDDATE
:
1682 /* concat the 32bit integers to a 64bit */
1683 u64File1
.LowPart
= lpFile1
->ftLastWriteTime
.dwLowDateTime
;
1684 u64File1
.HighPart
= lpFile1
->ftLastWriteTime
.dwHighDateTime
;
1685 u64File2
.LowPart
= lpFile2
->ftLastWriteTime
.dwLowDateTime
;
1686 u64File2
.HighPart
= lpFile2
->ftLastWriteTime
.dwHighDateTime
;
1690 /* In case that differnce is too big for a long */
1691 if (u64File1
.QuadPart
< u64File2
.QuadPart
)
1693 else if (u64File1
.QuadPart
> u64File2
.QuadPart
)
1700 /* Reverse if desired */
1701 if (lpFlags
->stOrderBy
.bCriteriaRev
[i
])
1704 /* If that criteria was enough for distinguishing
1705 the files/dirs,there is no need to calculate the others*/
1706 if (iComp
!= 0) break;
1709 /* Translate the value of iComp to boolean */
1719 * Sort files by the order criterias using quicksort method
1722 QsortFiles(LPWIN32_FIND_DATA ptrArray
[], /* [IN/OUT] The array with file info pointers */
1723 int i
, /* [IN] The index of first item in array */
1724 int j
, /* [IN] The index to last item in array */
1725 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags that we will use to sort */
1727 LPWIN32_FIND_DATA lpTemp
; /* A temporary pointer */
1728 int First
, Last
, Temp
;
1738 if (Way
== CompareFiles(ptrArray
[i
], ptrArray
[j
], lpFlags
))
1740 /* Swap the pointers of the array */
1741 lpTemp
= ptrArray
[i
];
1742 ptrArray
[i
]= ptrArray
[j
];
1743 ptrArray
[j
] = lpTemp
;
1745 /* Swap the indexes for inverting sorting */
1756 QsortFiles(ptrArray
,First
, i
-1, lpFlags
);
1757 QsortFiles(ptrArray
,i
+1,Last
, lpFlags
);
1766 * The functions that does everything except for printing results
1769 DirList(LPTSTR szPath
, /* [IN] The path that dir starts */
1770 LPTSTR szFilespec
, /* [IN] The type of file that we are looking for */
1771 LPINT pLine
, /* FIXME: Maybe used for paginating */
1772 LPDIRSWITCHFLAGS lpFlags
) /* [IN] The flags of the listing */
1774 HANDLE hSearch
; /* The handle of the search */
1775 HANDLE hRecSearch
; /* The handle for searching recursivly */
1776 WIN32_FIND_DATA wfdFileInfo
; /* The info of file that found */
1777 LPWIN32_FIND_DATA
* ptrFileArray
; /* An array of pointers with all the files */
1778 PDIRFINDLISTNODE ptrStartNode
; /* The pointer to the first node */
1779 PDIRFINDLISTNODE ptrNextNode
; /* A pointer used for relatives refernces */
1780 TCHAR szFullPath
[MAX_PATH
]; /* The full path that we are listing with trailing \ */
1781 TCHAR szFullFileSpec
[MAX_PATH
]; /* The full path with file specs that we ll request\ */
1782 DWORD dwCount
; /* A counter of files found in directory */
1783 DWORD dwCountFiles
; /* Counter for files */
1784 DWORD dwCountDirs
; /* Counter for directories */
1785 ULARGE_INTEGER u64CountBytes
; /* Counter for bytes */
1786 ULARGE_INTEGER u64Temp
; /* A temporary counter */
1788 /* Initialize Variables */
1789 ptrStartNode
= NULL
;
1794 u64CountBytes
.QuadPart
= 0;
1796 /* Create szFullPath and szFullFileSpec */
1797 _tcscpy (szFullPath
, szPath
);
1798 if (szFullPath
[_tcslen(szFullPath
) - 1] != _T('\\'))
1799 _tcscat (szFullPath
, _T("\\"));
1800 _tcscpy (szFullFileSpec
, szFullPath
);
1801 _tcscat (szFullFileSpec
, szFilespec
);
1803 /* Prepare the linked list, first node is allocated */
1804 ptrStartNode
= malloc(sizeof(DIRFINDLISTNODE
));
1805 if (ptrStartNode
== NULL
)
1808 ConErrPrintf(_T("DEBUG: Cannot allocate memory for ptrStartNode!\n"));
1810 return 1; /* Error cannot allocate memory for 1st object */
1812 ptrNextNode
= ptrStartNode
;
1814 /* Collect the results for the current folder */
1815 hSearch
= FindFirstFile(szFullFileSpec
, &wfdFileInfo
);
1818 if (hSearch
!= INVALID_HANDLE_VALUE
)
1820 /* Here we filter all the specified attributes */
1821 if ((wfdFileInfo
.dwFileAttributes
& lpFlags
->stAttribs
.dwAttribMask
)
1822 == (lpFlags
->stAttribs
.dwAttribMask
& lpFlags
->stAttribs
.dwAttribVal
))
1824 ptrNextNode
->ptrNext
= malloc(sizeof(DIRFINDLISTNODE
));
1825 if (ptrNextNode
->ptrNext
== NULL
)
1828 ConErrPrintf(_T("DEBUG: Cannot allocate memory for ptrNextNode->ptrNext!\n"));
1830 while (ptrStartNode
)
1832 ptrNextNode
= ptrStartNode
->ptrNext
;
1834 ptrStartNode
= ptrNextNode
;
1840 /* If malloc fails we go to next file in hope it works,
1841 without braking the linked list! */
1842 if (ptrNextNode
->ptrNext
)
1844 /* Copy the info of search at linked list */
1845 memcpy(&ptrNextNode
->ptrNext
->stFindInfo
,
1847 sizeof(WIN32_FIND_DATA
));
1849 /* If lower case is selected do it here */
1850 if (lpFlags
->bLowerCase
)
1852 _tcslwr(ptrNextNode
->ptrNext
->stFindInfo
.cAlternateFileName
);
1853 _tcslwr(ptrNextNode
->ptrNext
->stFindInfo
.cFileName
);
1856 /* Continue at next node at linked list */
1857 ptrNextNode
= ptrNextNode
->ptrNext
;
1860 /* Grab statistics */
1861 if (wfdFileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
)
1870 u64Temp
.HighPart
= wfdFileInfo
.nFileSizeHigh
;
1871 u64Temp
.LowPart
= wfdFileInfo
.nFileSizeLow
;
1872 u64CountBytes
.QuadPart
+= u64Temp
.QuadPart
;
1877 }while(FindNextFile(hSearch
, &wfdFileInfo
));
1880 /* Terminate list */
1881 ptrNextNode
->ptrNext
= NULL
;
1883 /* Calculate and allocate space need for making an array of pointers */
1884 ptrFileArray
= malloc(sizeof(LPWIN32_FIND_DATA
) * dwCount
);
1885 if (ptrFileArray
== NULL
)
1888 ConErrPrintf(_T("DEBUG: Cannot allocate memory for ptrFileArray!\n"));
1890 while (ptrStartNode
)
1892 ptrNextNode
= ptrStartNode
->ptrNext
;
1894 ptrStartNode
= ptrNextNode
;
1901 * Create an array of pointers from the linked list
1902 * this will be used to sort and print data, rather than the list
1904 ptrNextNode
= ptrStartNode
;
1906 while (ptrNextNode
->ptrNext
)
1908 *(ptrFileArray
+ dwCount
) = &ptrNextNode
->ptrNext
->stFindInfo
;
1909 ptrNextNode
= ptrNextNode
->ptrNext
;
1913 /* Sort Data if requested*/
1914 if (lpFlags
->stOrderBy
.sCriteriaCount
> 0)
1915 QsortFiles(ptrFileArray
, 0, dwCount
-1,lpFlags
);
1918 DirPrintFiles(ptrFileArray
, dwCount
, szFullPath
, lpFlags
);
1922 if (CheckCtrlBreak(BREAK_INPUT
))
1926 /* Add statistics to recursive statistics*/
1927 recurse_dir_cnt
+= dwCountDirs
;
1928 recurse_file_cnt
+= dwCountFiles
;
1929 recurse_bytes
.QuadPart
+= u64CountBytes
.QuadPart
;
1931 /* Do the recursive job if requested
1932 the recursive is be done on ALL(indepent of their attribs)
1933 directoried of the current one.*/
1934 if (lpFlags
->bRecursive
)
1936 /* The new search is involving any *.* file */
1937 _tcscpy(szFullFileSpec
, szFullPath
);
1938 _tcscat(szFullFileSpec
, _T("*.*"));
1939 hRecSearch
= FindFirstFile (szFullFileSpec
, &wfdFileInfo
);
1942 if (hRecSearch
!= INVALID_HANDLE_VALUE
)
1944 /* We search for directories other than "." and ".." */
1945 if ((_tcsicmp(wfdFileInfo
.cFileName
, _T(".")) != 0) &&
1946 (_tcsicmp(wfdFileInfo
.cFileName
, _T("..")) != 0 ) &&
1947 (wfdFileInfo
.dwFileAttributes
& FILE_ATTRIBUTE_DIRECTORY
))
1949 /* Concat the path and the directory to do recursive */
1950 _tcscpy(szFullFileSpec
, szFullPath
);
1951 _tcscat(szFullFileSpec
, wfdFileInfo
.cFileName
);
1952 /* We do the same for tha folder */
1953 if (DirList(szFullFileSpec
, szFilespec
, pLine
,lpFlags
) != 0)
1959 }while(FindNextFile(hRecSearch
,&wfdFileInfo
));
1960 FindClose(hRecSearch
);
1963 /* Free linked list */
1964 while (ptrStartNode
)
1966 ptrNextNode
= ptrStartNode
->ptrNext
;
1968 ptrStartNode
= ptrNextNode
;
1980 * internal dir command
1983 CommandDir(LPTSTR first
, LPTSTR rest
)
1985 TCHAR dircmd
[256]; /* A variable to store the DIRCMD enviroment variable */
1987 TCHAR szPath
[MAX_PATH
];
1988 TCHAR szFilespec
[MAX_PATH
];
1993 DIRSWITCHFLAGS stFlags
;
1995 /* Initialize variables */
1997 recurse_dir_cnt
= 0L;
1998 recurse_file_cnt
= 0L;
1999 recurse_bytes
.QuadPart
= 0;
2001 /* Initialize Switch Flags < Default switches are setted here!> */
2002 stFlags
.b4Digit
= TRUE
;
2003 stFlags
.bBareFormat
= FALSE
;
2004 stFlags
.bLowerCase
= FALSE
;
2005 stFlags
.bNewLongList
= TRUE
;
2006 stFlags
.bPause
= FALSE
;
2007 stFlags
.bRecursive
= FALSE
;
2008 stFlags
.bShortName
= FALSE
;
2009 stFlags
.bTSeperator
= TRUE
;
2010 stFlags
.bUser
= FALSE
;
2011 stFlags
.bWideList
= FALSE
;
2012 stFlags
.bWideListColSort
= FALSE
;
2013 stFlags
.stTimeField
.eTimeField
= TF_MODIFIEDDATE
;
2014 stFlags
.stTimeField
.bUnSet
= FALSE
;
2015 stFlags
.stAttribs
.dwAttribMask
= FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_SYSTEM
;
2016 stFlags
.stAttribs
.dwAttribVal
= 0L;
2017 stFlags
.stAttribs
.bUnSet
= FALSE
;
2018 stFlags
.stOrderBy
.sCriteriaCount
= 0;
2019 stFlags
.stOrderBy
.bUnSet
= FALSE
;
2023 /* read the parameters from the DIRCMD environment variable */
2024 if (GetEnvironmentVariable (_T("DIRCMD"), dircmd
, 256))
2025 if (!DirReadParam(dircmd
, ¶ms
, &entries
, &stFlags
))
2031 /* read the parameters */
2032 if (!DirReadParam(rest
, ¶ms
, &entries
, &stFlags
) || CheckCtrlBreak(BREAK_INPUT
))
2038 /* default to current directory */
2040 if(!add_entry(&entries
, ¶ms
, _T("."))) {
2046 for(loop
= 0; loop
< entries
; loop
++)
2048 /* parse the directory info */
2049 if (DirParsePathspec (params
[loop
], szPath
, szFilespec
) || CheckCtrlBreak(BREAK_INPUT
))
2056 Uncomment this to show the final state of switch flags*/
2060 ConOutPrintf(_T("Attributes mask/value %x/%x\n"),stFlags
.stAttribs
.dwAttribMask
,stFlags
.stAttribs
.dwAttribVal
);
2061 ConOutPrintf(_T("(B) Bare format : %i\n"), stFlags
.bBareFormat
);
2062 ConOutPrintf(_T("(C) Thousand : %i\n"), stFlags
.bTSeperator
);
2063 ConOutPrintf(_T("(W) Wide list : %i\n"), stFlags
.bWideList
);
2064 ConOutPrintf(_T("(D) Wide list sort by column : %i\n"), stFlags
.bWideListColSort
);
2065 ConOutPrintf(_T("(L) Lowercase : %i\n"), stFlags
.bLowerCase
);
2066 ConOutPrintf(_T("(N) New : %i\n"), stFlags
.bNewLongList
);
2067 ConOutPrintf(_T("(O) Order : %i\n"), stFlags
.stOrderBy
.sCriteriaCount
);
2068 for (i
=0;i
<stFlags
.stOrderBy
.sCriteriaCount
;i
++)
2069 ConOutPrintf(_T(" Order Criteria [%i]: %i (Reversed: %i)\n"),i
, stFlags
.stOrderBy
.eCriteria
[i
], stFlags
.stOrderBy
.bCriteriaRev
[i
] );
2070 ConOutPrintf(_T("(P) Pause : %i\n"), stFlags
.bPause
);
2071 ConOutPrintf(_T("(Q) Owner : %i\n"), stFlags
.bUser
);
2072 ConOutPrintf(_T("(S) Recursive : %i\n"), stFlags
.bRecursive
);
2073 ConOutPrintf(_T("(T) Time field : %i\n"), stFlags
.stTimeField
.eTimeField
);
2074 ConOutPrintf(_T("(X) Short names : %i\n"), stFlags
.bShortName
);
2075 ConOutPrintf(_T("Parameter : %s\n"), params
[loop
] );
2079 /* Print the drive header if the drive changed */
2080 if(cDrive
!= szPath
[0] && !stFlags
.bBareFormat
) {
2081 if (!PrintDirectoryHeader (szPath
, &nLine
, &stFlags
)) {
2090 /* do the actual dir */
2091 if (DirList (szPath
, szFilespec
, &nLine
, &stFlags
))
2098 /* print the footer */
2099 PrintSummary(szPath
,