cmd.exe: Add basic support for FOR /F parsing launched programs output.
[wine.git] / programs / cmd / directory.c
blob0de5bb8d2c923a09d473003f6360a0038bcc8732
1 /*
2 * CMD - Wine-compatible command line interface - Directory functions.
4 * Copyright (C) 1999 D A Pickles
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTES:
23 * On entry, global variables quals, param1, param2 contain
24 * the qualifiers (uppercased and concatenated) and parameters entered, with
25 * environment-variable and batch parameter substitution already done.
28 #define WIN32_LEAN_AND_MEAN
30 #include "wcmd.h"
31 #include "wine/debug.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(cmd);
35 int WCMD_dir_sort (const void *a, const void *b);
36 WCHAR * WCMD_filesize64 (ULONGLONG free);
37 WCHAR * WCMD_strrev (WCHAR *buff);
38 static void WCMD_getfileowner(WCHAR *filename, WCHAR *owner, int ownerlen);
39 static void WCMD_dir_trailer(WCHAR drive);
41 extern int echo_mode;
42 extern WCHAR quals[MAX_PATH], param1[MAX_PATH], param2[MAX_PATH];
43 extern DWORD errorlevel;
45 typedef enum _DISPLAYTIME
47 Creation = 0,
48 Access,
49 Written
50 } DISPLAYTIME;
52 typedef enum _DISPLAYORDER
54 Name = 0,
55 Extension,
56 Size,
57 Date
58 } DISPLAYORDER;
60 static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *parms, int level);
61 static int file_total, dir_total, recurse, wide, bare, max_width, lower;
62 static int shortname, usernames;
63 static ULONGLONG byte_total;
64 static DISPLAYTIME dirTime;
65 static DISPLAYORDER dirOrder;
66 static BOOL orderReverse, orderGroupDirs, orderGroupDirsReverse, orderByCol;
67 static BOOL separator;
68 static ULONG showattrs, attrsbits;
70 static const WCHAR dotW[] = {'.','\0'};
71 static const WCHAR dotdotW[] = {'.','.','\0'};
72 static const WCHAR starW[] = {'*','\0'};
73 static const WCHAR slashW[] = {'\\','\0'};
74 static const WCHAR emptyW[] = {'\0'};
75 static const WCHAR spaceW[] = {' ','\0'};
77 /*****************************************************************************
78 * WCMD_directory
80 * List a file directory.
84 void WCMD_directory (WCHAR *cmd) {
86 WCHAR path[MAX_PATH], cwd[MAX_PATH];
87 int status, paged_mode;
88 CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
89 WCHAR *p;
90 WCHAR string[MAXSTRING];
91 int argno = 0;
92 int argsProcessed = 0;
93 WCHAR *argN = cmd;
94 WCHAR lastDrive;
95 BOOL trailerReqd = FALSE;
96 DIRECTORY_STACK *fullParms = NULL;
97 DIRECTORY_STACK *prevEntry = NULL;
98 DIRECTORY_STACK *thisEntry = NULL;
99 WCHAR drive[10];
100 WCHAR dir[MAX_PATH];
101 WCHAR fname[MAX_PATH];
102 WCHAR ext[MAX_PATH];
103 static const WCHAR dircmdW[] = {'D','I','R','C','M','D','\0'};
105 errorlevel = 0;
107 /* Prefill Quals with (uppercased) DIRCMD env var */
108 if (GetEnvironmentVariable (dircmdW, string, sizeof(string)/sizeof(WCHAR))) {
109 p = string;
110 while ( (*p = toupper(*p)) ) ++p;
111 strcatW(string,quals);
112 strcpyW(quals, string);
115 byte_total = 0;
116 file_total = dir_total = 0;
118 /* Initialize all flags to their defaults as if no DIRCMD or quals */
119 paged_mode = FALSE;
120 recurse = FALSE;
121 wide = FALSE;
122 bare = FALSE;
123 lower = FALSE;
124 shortname = FALSE;
125 usernames = FALSE;
126 orderByCol = FALSE;
127 separator = TRUE;
128 dirTime = Written;
129 dirOrder = Name;
130 orderReverse = FALSE;
131 orderGroupDirs = FALSE;
132 orderGroupDirsReverse = FALSE;
133 showattrs = 0;
134 attrsbits = 0;
136 /* Handle args - Loop through so right most is the effective one */
137 /* Note: /- appears to be a negate rather than an off, eg. dir
138 /-W is wide, or dir /w /-w /-w is also wide */
139 p = quals;
140 while (*p && (*p=='/' || *p==' ')) {
141 BOOL negate = FALSE;
142 if (*p++==' ') continue; /* Skip / and blanks introduced through DIRCMD */
144 if (*p=='-') {
145 negate = TRUE;
146 p++;
149 WINE_TRACE("Processing arg '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
150 switch (*p) {
151 case 'P': if (negate) paged_mode = !paged_mode;
152 else paged_mode = TRUE;
153 break;
154 case 'S': if (negate) recurse = !recurse;
155 else recurse = TRUE;
156 break;
157 case 'W': if (negate) wide = !wide;
158 else wide = TRUE;
159 break;
160 case 'B': if (negate) bare = !bare;
161 else bare = TRUE;
162 break;
163 case 'L': if (negate) lower = !lower;
164 else lower = TRUE;
165 break;
166 case 'X': if (negate) shortname = !shortname;
167 else shortname = TRUE;
168 break;
169 case 'Q': if (negate) usernames = !usernames;
170 else usernames = TRUE;
171 break;
172 case 'D': if (negate) orderByCol = !orderByCol;
173 else orderByCol = TRUE;
174 break;
175 case 'C': if (negate) separator = !separator;
176 else separator = TRUE;
177 break;
178 case 'T': p = p + 1;
179 if (*p==':') p++; /* Skip optional : */
181 if (*p == 'A') dirTime = Access;
182 else if (*p == 'C') dirTime = Creation;
183 else if (*p == 'W') dirTime = Written;
185 /* Support /T and /T: with no parms, default to written */
186 else if (*p == 0x00 || *p == '/') {
187 dirTime = Written;
188 p = p - 1; /* So when step on, move to '/' */
189 } else {
190 SetLastError(ERROR_INVALID_PARAMETER);
191 WCMD_print_error();
192 errorlevel = 1;
193 return;
195 break;
196 case 'O': p = p + 1;
197 if (*p==':') p++; /* Skip optional : */
198 while (*p && *p != '/') {
199 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
200 switch (*p) {
201 case 'N': dirOrder = Name; break;
202 case 'E': dirOrder = Extension; break;
203 case 'S': dirOrder = Size; break;
204 case 'D': dirOrder = Date; break;
205 case '-': if (*(p+1)=='G') orderGroupDirsReverse=TRUE;
206 else orderReverse = TRUE;
207 break;
208 case 'G': orderGroupDirs = TRUE; break;
209 default:
210 SetLastError(ERROR_INVALID_PARAMETER);
211 WCMD_print_error();
212 errorlevel = 1;
213 return;
215 p++;
217 p = p - 1; /* So when step on, move to '/' */
218 break;
219 case 'A': p = p + 1;
220 showattrs = 0;
221 attrsbits = 0;
222 if (*p==':') p++; /* Skip optional : */
223 while (*p && *p != '/') {
224 BOOL anegate = FALSE;
225 ULONG mask;
227 /* Note /A: - options are 'offs' not toggles */
228 if (*p=='-') {
229 anegate = TRUE;
230 p++;
233 WINE_TRACE("Processing subparm '%c' (in %s)\n", *p, wine_dbgstr_w(quals));
234 switch (*p) {
235 case 'D': mask = FILE_ATTRIBUTE_DIRECTORY; break;
236 case 'H': mask = FILE_ATTRIBUTE_HIDDEN; break;
237 case 'S': mask = FILE_ATTRIBUTE_SYSTEM; break;
238 case 'R': mask = FILE_ATTRIBUTE_READONLY; break;
239 case 'A': mask = FILE_ATTRIBUTE_ARCHIVE; break;
240 default:
241 SetLastError(ERROR_INVALID_PARAMETER);
242 WCMD_print_error();
243 errorlevel = 1;
244 return;
247 /* Keep running list of bits we care about */
248 attrsbits |= mask;
250 /* Mask shows what MUST be in the bits we care about */
251 if (anegate) showattrs = showattrs & ~mask;
252 else showattrs |= mask;
254 p++;
256 p = p - 1; /* So when step on, move to '/' */
257 WINE_TRACE("Result: showattrs %x, bits %x\n", showattrs, attrsbits);
258 break;
259 default:
260 SetLastError(ERROR_INVALID_PARAMETER);
261 WCMD_print_error();
262 errorlevel = 1;
263 return;
265 p = p + 1;
268 /* Handle conflicting args and initialization */
269 if (bare || shortname) wide = FALSE;
270 if (bare) shortname = FALSE;
271 if (wide) usernames = FALSE;
272 if (orderByCol) wide = TRUE;
274 if (wide) {
275 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleInfo))
276 max_width = consoleInfo.dwSize.X;
277 else
278 max_width = 80;
280 if (paged_mode) {
281 WCMD_enter_paged_mode(NULL);
284 argno = 0;
285 argsProcessed = 0;
286 argN = cmd;
287 GetCurrentDirectory (MAX_PATH, cwd);
288 strcatW(cwd, slashW);
290 /* Loop through all args, calculating full effective directory */
291 fullParms = NULL;
292 prevEntry = NULL;
293 while (argN) {
294 WCHAR fullname[MAXSTRING];
295 WCHAR *thisArg = WCMD_parameter (cmd, argno++, &argN);
296 if (argN && argN[0] != '/') {
298 WINE_TRACE("Found parm '%s'\n", wine_dbgstr_w(thisArg));
299 if (thisArg[1] == ':' && thisArg[2] == '\\') {
300 strcpyW(fullname, thisArg);
301 } else if (thisArg[1] == ':' && thisArg[2] != '\\') {
302 WCHAR envvar[4];
303 static const WCHAR envFmt[] = {'=','%','c',':','\0'};
304 wsprintf(envvar, envFmt, thisArg[0]);
305 if (!GetEnvironmentVariable(envvar, fullname, MAX_PATH)) {
306 static const WCHAR noEnvFmt[] = {'%','c',':','\0'};
307 wsprintf(fullname, noEnvFmt, thisArg[0]);
309 strcatW(fullname, slashW);
310 strcatW(fullname, &thisArg[2]);
311 } else if (thisArg[0] == '\\') {
312 memcpy(fullname, cwd, 2 * sizeof(WCHAR));
313 strcpyW(fullname+2, thisArg);
314 } else {
315 strcpyW(fullname, cwd);
316 strcatW(fullname, thisArg);
318 WINE_TRACE("Using location '%s'\n", wine_dbgstr_w(fullname));
320 status = GetFullPathName (fullname, sizeof(path)/sizeof(WCHAR), path, NULL);
323 * If the path supplied does not include a wildcard, and the endpoint of the
324 * path references a directory, we need to list the *contents* of that
325 * directory not the directory file itself.
327 if ((strchrW(path, '*') == NULL) && (strchrW(path, '%') == NULL)) {
328 status = GetFileAttributes (path);
329 if ((status != INVALID_FILE_ATTRIBUTES) && (status & FILE_ATTRIBUTE_DIRECTORY)) {
330 if (path[strlenW(path)-1] == '\\') {
331 strcatW (path, starW);
333 else {
334 const WCHAR slashStarW[] = {'\\','*','\0'};
335 strcatW (path, slashStarW);
338 } else {
339 /* Special case wildcard search with no extension (ie parameters ending in '.') as
340 GetFullPathName strips off the additional '.' */
341 if (fullname[strlenW(fullname)-1] == '.') strcatW(path, dotW);
344 WINE_TRACE("Using path '%s'\n", wine_dbgstr_w(path));
345 thisEntry = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
346 if (fullParms == NULL) fullParms = thisEntry;
347 if (prevEntry != NULL) prevEntry->next = thisEntry;
348 prevEntry = thisEntry;
349 thisEntry->next = NULL;
351 /* Split into components */
352 WCMD_splitpath(path, drive, dir, fname, ext);
353 WINE_TRACE("Path Parts: drive: '%s' dir: '%s' name: '%s' ext:'%s'\n",
354 wine_dbgstr_w(drive), wine_dbgstr_w(dir),
355 wine_dbgstr_w(fname), wine_dbgstr_w(ext));
357 thisEntry->dirName = HeapAlloc(GetProcessHeap(),0,
358 sizeof(WCHAR) * (strlenW(drive)+strlenW(dir)+1));
359 strcpyW(thisEntry->dirName, drive);
360 strcatW(thisEntry->dirName, dir);
362 thisEntry->fileName = HeapAlloc(GetProcessHeap(),0,
363 sizeof(WCHAR) * (strlenW(fname)+strlenW(ext)+1));
364 strcpyW(thisEntry->fileName, fname);
365 strcatW(thisEntry->fileName, ext);
370 /* If just 'dir' entered, a '*' parameter is assumed */
371 if (fullParms == NULL) {
372 WINE_TRACE("Inserting default '*'\n");
373 fullParms = HeapAlloc(GetProcessHeap(),0, sizeof(DIRECTORY_STACK));
374 fullParms->next = NULL;
375 fullParms->dirName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * (strlenW(cwd)+1));
376 strcpyW(fullParms->dirName, cwd);
377 fullParms->fileName = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR) * 2);
378 strcpyW(fullParms->fileName, starW);
381 lastDrive = '?';
382 prevEntry = NULL;
383 thisEntry = fullParms;
384 trailerReqd = FALSE;
386 while (thisEntry != NULL) {
388 /* Output disk free (trailer) and volume information (header) if the drive
389 letter changes */
390 if (lastDrive != toupper(thisEntry->dirName[0])) {
392 /* Trailer Information */
393 if (lastDrive != '?') {
394 trailerReqd = FALSE;
395 WCMD_dir_trailer(prevEntry->dirName[0]);
398 lastDrive = toupper(thisEntry->dirName[0]);
400 if (!bare) {
401 WCHAR drive[3];
403 WINE_TRACE("Writing volume for '%c:'\n", thisEntry->dirName[0]);
404 memcpy(drive, thisEntry->dirName, 2 * sizeof(WCHAR));
405 drive[2] = 0x00;
406 status = WCMD_volume (0, drive);
407 trailerReqd = TRUE;
408 if (!status) {
409 errorlevel = 1;
410 goto exit;
413 } else {
414 static const WCHAR newLine2[] = {'\n','\n','\0'};
415 if (!bare) WCMD_output (newLine2);
418 /* Clear any errors from previous invocations, and process it */
419 errorlevel = 0;
420 prevEntry = thisEntry;
421 thisEntry = WCMD_list_directory (thisEntry, 0);
424 /* Trailer Information */
425 if (trailerReqd) {
426 WCMD_dir_trailer(prevEntry->dirName[0]);
429 exit:
430 if (paged_mode) WCMD_leave_paged_mode();
432 /* Free storage allocated for parms */
433 while (fullParms != NULL) {
434 prevEntry = fullParms;
435 fullParms = prevEntry->next;
436 HeapFree(GetProcessHeap(),0,prevEntry->dirName);
437 HeapFree(GetProcessHeap(),0,prevEntry->fileName);
438 HeapFree(GetProcessHeap(),0,prevEntry);
442 /*****************************************************************************
443 * WCMD_list_directory
445 * List a single file directory. This function (and those below it) can be called
446 * recursively when the /S switch is used.
448 * FIXME: Assumes 24-line display for the /P qualifier.
451 static DIRECTORY_STACK *WCMD_list_directory (DIRECTORY_STACK *inputparms, int level) {
453 WCHAR string[1024], datestring[32], timestring[32];
454 WCHAR real_path[MAX_PATH];
455 WIN32_FIND_DATA *fd;
456 FILETIME ft;
457 SYSTEMTIME st;
458 HANDLE hff;
459 int dir_count, file_count, entry_count, i, widest, cur_width, tmp_width;
460 int numCols, numRows;
461 int rows, cols;
462 ULARGE_INTEGER byte_count, file_size;
463 DIRECTORY_STACK *parms;
464 int concurrentDirs = 0;
465 BOOL done_header = FALSE;
467 static const WCHAR fmtDir[] = {'%','1','0','s',' ',' ','%','8','s',' ',' ',
468 '<','D','I','R','>',' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
469 static const WCHAR fmtFile[] = {'%','1','0','s',' ',' ','%','8','s',' ',' ',
470 ' ',' ','%','1','0','s',' ',' ','\0'};
471 static const WCHAR fmt2[] = {'%','-','1','3','s','\0'};
472 static const WCHAR fmt3[] = {'%','-','2','3','s','\0'};
473 static const WCHAR fmt4[] = {'%','s','\0'};
474 static const WCHAR fmt5[] = {'%','s','%','s','\0'};
476 dir_count = 0;
477 file_count = 0;
478 entry_count = 0;
479 byte_count.QuadPart = 0;
480 widest = 0;
481 cur_width = 0;
483 /* Loop merging all the files from consecutive parms which relate to the
484 same directory. Note issuing a directory header with no contents
485 mirrors what windows does */
486 parms = inputparms;
487 fd = HeapAlloc(GetProcessHeap(),0,sizeof(WIN32_FIND_DATA));
488 while (parms && strcmpW(inputparms->dirName, parms->dirName) == 0) {
489 concurrentDirs++;
491 /* Work out the full path + filename */
492 strcpyW(real_path, parms->dirName);
493 strcatW(real_path, parms->fileName);
495 /* Load all files into an in memory structure */
496 WINE_TRACE("Looking for matches to '%s'\n", wine_dbgstr_w(real_path));
497 hff = FindFirstFile (real_path, (fd+entry_count));
498 if (hff != INVALID_HANDLE_VALUE) {
499 do {
500 /* Skip any which are filtered out by attribute */
501 if (((fd+entry_count)->dwFileAttributes & attrsbits) != showattrs) continue;
503 entry_count++;
505 /* Keep running track of longest filename for wide output */
506 if (wide || orderByCol) {
507 int tmpLen = strlenW((fd+(entry_count-1))->cFileName) + 3;
508 if ((fd+(entry_count-1))->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) tmpLen = tmpLen + 2;
509 if (tmpLen > widest) widest = tmpLen;
512 fd = HeapReAlloc(GetProcessHeap(),0,fd,(entry_count+1)*sizeof(WIN32_FIND_DATA));
513 if (fd == NULL) {
514 FindClose (hff);
515 WINE_ERR("Out of memory\n");
516 errorlevel = 1;
517 return parms->next;
519 } while (FindNextFile(hff, (fd+entry_count)) != 0);
520 FindClose (hff);
523 /* Work out the actual current directory name without a trailing \ */
524 strcpyW(real_path, parms->dirName);
525 real_path[strlenW(parms->dirName)-1] = 0x00;
527 /* Output the results */
528 if (!bare) {
529 if (level != 0 && (entry_count > 0)) WCMD_output (newline);
530 if (!recurse || ((entry_count > 0) && done_header==FALSE)) {
531 static const WCHAR headerW[] = {'D','i','r','e','c','t','o','r','y',' ','o','f',
532 ' ','%','s','\n','\n','\0'};
533 WCMD_output (headerW, real_path);
534 done_header = TRUE;
538 /* Move to next parm */
539 parms = parms->next;
542 /* Handle case where everything is filtered out */
543 if (entry_count > 0) {
545 /* Sort the list of files */
546 qsort (fd, entry_count, sizeof(WIN32_FIND_DATA), WCMD_dir_sort);
548 /* Work out the number of columns */
549 WINE_TRACE("%d entries, maxwidth=%d, widest=%d\n", entry_count, max_width, widest);
550 if (wide || orderByCol) {
551 numCols = max(1, (int)max_width / widest);
552 numRows = entry_count / numCols;
553 if (entry_count % numCols) numRows++;
554 } else {
555 numCols = 1;
556 numRows = entry_count;
558 WINE_TRACE("cols=%d, rows=%d\n", numCols, numRows);
560 for (rows=0; rows<numRows; rows++) {
561 BOOL addNewLine = TRUE;
562 for (cols=0; cols<numCols; cols++) {
563 WCHAR username[24];
565 /* Work out the index of the entry being pointed to */
566 if (orderByCol) {
567 i = (cols * numRows) + rows;
568 if (i >= entry_count) continue;
569 } else {
570 i = (rows * numCols) + cols;
571 if (i >= entry_count) continue;
574 /* /L convers all names to lower case */
575 if (lower) {
576 WCHAR *p = (fd+i)->cFileName;
577 while ( (*p = tolower(*p)) ) ++p;
580 /* /Q gets file ownership information */
581 if (usernames) {
582 strcpyW (string, inputparms->dirName);
583 strcatW (string, (fd+i)->cFileName);
584 WCMD_getfileowner(string, username, sizeof(username)/sizeof(WCHAR));
587 if (dirTime == Written) {
588 FileTimeToLocalFileTime (&(fd+i)->ftLastWriteTime, &ft);
589 } else if (dirTime == Access) {
590 FileTimeToLocalFileTime (&(fd+i)->ftLastAccessTime, &ft);
591 } else {
592 FileTimeToLocalFileTime (&(fd+i)->ftCreationTime, &ft);
594 FileTimeToSystemTime (&ft, &st);
595 GetDateFormat (0, DATE_SHORTDATE, &st, NULL, datestring,
596 sizeof(datestring)/sizeof(WCHAR));
597 GetTimeFormat (0, TIME_NOSECONDS, &st,
598 NULL, timestring, sizeof(timestring)/sizeof(WCHAR));
600 if (wide) {
602 tmp_width = cur_width;
603 if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
604 static const WCHAR fmt[] = {'[','%','s',']','\0'};
605 WCMD_output (fmt, (fd+i)->cFileName);
606 dir_count++;
607 tmp_width = tmp_width + strlenW((fd+i)->cFileName) + 2;
608 } else {
609 static const WCHAR fmt[] = {'%','s','\0'};
610 WCMD_output (fmt, (fd+i)->cFileName);
611 tmp_width = tmp_width + strlenW((fd+i)->cFileName) ;
612 file_count++;
613 file_size.u.LowPart = (fd+i)->nFileSizeLow;
614 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
615 byte_count.QuadPart += file_size.QuadPart;
617 cur_width = cur_width + widest;
619 if ((cur_width + widest) > max_width) {
620 cur_width = 0;
621 } else {
622 int padding = cur_width - tmp_width;
623 int toWrite = 0;
624 WCHAR temp[101];
626 /* Note: WCMD_output uses wvsprintf which does not allow %*
627 so manually pad with spaces to appropriate width */
628 strcpyW(temp, emptyW);
629 while (padding > 0) {
630 strcatW(&temp[toWrite], spaceW);
631 toWrite++;
632 if (toWrite > 99) {
633 WCMD_output(temp);
634 toWrite = 0;
635 strcpyW(temp, emptyW);
637 padding--;
639 WCMD_output(temp);
642 } else if ((fd+i)->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
643 dir_count++;
645 if (!bare) {
646 WCMD_output (fmtDir, datestring, timestring);
647 if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
648 if (usernames) WCMD_output (fmt3, username);
649 WCMD_output(fmt4,(fd+i)->cFileName);
650 } else {
651 if (!((strcmpW((fd+i)->cFileName, dotW) == 0) ||
652 (strcmpW((fd+i)->cFileName, dotdotW) == 0))) {
653 WCMD_output (fmt5, recurse?inputparms->dirName:emptyW, (fd+i)->cFileName);
654 } else {
655 addNewLine = FALSE;
659 else {
660 file_count++;
661 file_size.u.LowPart = (fd+i)->nFileSizeLow;
662 file_size.u.HighPart = (fd+i)->nFileSizeHigh;
663 byte_count.QuadPart += file_size.QuadPart;
664 if (!bare) {
665 WCMD_output (fmtFile, datestring, timestring,
666 WCMD_filesize64(file_size.QuadPart));
667 if (shortname) WCMD_output (fmt2, (fd+i)->cAlternateFileName);
668 if (usernames) WCMD_output (fmt3, username);
669 WCMD_output(fmt4,(fd+i)->cFileName);
670 } else {
671 WCMD_output (fmt5, recurse?inputparms->dirName:emptyW, (fd+i)->cFileName);
675 if (addNewLine) WCMD_output (newline);
676 cur_width = 0;
679 if (!bare) {
680 if (file_count == 1) {
681 static const WCHAR fmt[] = {' ',' ',' ',' ',' ',' ',' ','1',' ','f','i','l','e',' ',
682 '%','2','5','s',' ','b','y','t','e','s','\n','\0'};
683 WCMD_output (fmt, WCMD_filesize64 (byte_count.QuadPart));
685 else {
686 static const WCHAR fmt[] = {'%','8','d',' ','f','i','l','e','s',' ','%','2','4','s',
687 ' ','b','y','t','e','s','\n','\0'};
688 WCMD_output (fmt, file_count, WCMD_filesize64 (byte_count.QuadPart));
691 byte_total = byte_total + byte_count.QuadPart;
692 file_total = file_total + file_count;
693 dir_total = dir_total + dir_count;
695 if (!bare && !recurse) {
696 if (dir_count == 1) {
697 static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','y',
698 ' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
699 WCMD_output (fmt, 1);
700 } else {
701 static const WCHAR fmt[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','i',
702 'e','s','\0'};
703 WCMD_output (fmt, dir_count);
707 HeapFree(GetProcessHeap(),0,fd);
709 /* When recursing, look in all subdirectories for matches */
710 if (recurse) {
711 DIRECTORY_STACK *dirStack = NULL;
712 DIRECTORY_STACK *lastEntry = NULL;
713 WIN32_FIND_DATA finddata;
715 /* Build path to search */
716 strcpyW(string, inputparms->dirName);
717 strcatW(string, starW);
719 WINE_TRACE("Recursive, looking for '%s'\n", wine_dbgstr_w(string));
720 hff = FindFirstFile (string, &finddata);
721 if (hff != INVALID_HANDLE_VALUE) {
722 do {
723 if ((finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
724 (strcmpW(finddata.cFileName, dotdotW) != 0) &&
725 (strcmpW(finddata.cFileName, dotW) != 0)) {
727 DIRECTORY_STACK *thisDir;
728 int dirsToCopy = concurrentDirs;
730 /* Loop creating list of subdirs for all concurrent entries */
731 parms = inputparms;
732 while (dirsToCopy > 0) {
733 dirsToCopy--;
735 /* Work out search parameter in sub dir */
736 strcpyW (string, inputparms->dirName);
737 strcatW (string, finddata.cFileName);
738 strcatW (string, slashW);
739 WINE_TRACE("Recursive, Adding to search list '%s'\n", wine_dbgstr_w(string));
741 /* Allocate memory, add to list */
742 thisDir = HeapAlloc(GetProcessHeap(),0,sizeof(DIRECTORY_STACK));
743 if (dirStack == NULL) dirStack = thisDir;
744 if (lastEntry != NULL) lastEntry->next = thisDir;
745 lastEntry = thisDir;
746 thisDir->next = NULL;
747 thisDir->dirName = HeapAlloc(GetProcessHeap(),0,
748 sizeof(WCHAR) * (strlenW(string)+1));
749 strcpyW(thisDir->dirName, string);
750 thisDir->fileName = HeapAlloc(GetProcessHeap(),0,
751 sizeof(WCHAR) * (strlenW(parms->fileName)+1));
752 strcpyW(thisDir->fileName, parms->fileName);
753 parms = parms->next;
756 } while (FindNextFile(hff, &finddata) != 0);
757 FindClose (hff);
759 while (dirStack != NULL) {
760 DIRECTORY_STACK *thisDir = dirStack;
761 dirStack = WCMD_list_directory (thisDir, 1);
762 while (thisDir != dirStack) {
763 DIRECTORY_STACK *tempDir = thisDir->next;
764 HeapFree(GetProcessHeap(),0,thisDir->dirName);
765 HeapFree(GetProcessHeap(),0,thisDir->fileName);
766 HeapFree(GetProcessHeap(),0,thisDir);
767 thisDir = tempDir;
773 /* Handle case where everything is filtered out */
774 if ((file_total + dir_total == 0) && (level == 0)) {
775 SetLastError (ERROR_FILE_NOT_FOUND);
776 WCMD_print_error ();
777 errorlevel = 1;
780 return parms;
783 /*****************************************************************************
784 * WCMD_filesize64
786 * Convert a 64-bit number into a WCHARacter string, with commas every three digits.
787 * Result is returned in a static string overwritten with each call.
788 * FIXME: There must be a better algorithm!
791 WCHAR * WCMD_filesize64 (ULONGLONG n) {
793 ULONGLONG q;
794 unsigned int r, i;
795 WCHAR *p;
796 static WCHAR buff[32];
798 p = buff;
799 i = -3;
800 do {
801 if (separator && ((++i)%3 == 1)) *p++ = ',';
802 q = n / 10;
803 r = n - (q * 10);
804 *p++ = r + '0';
805 *p = '\0';
806 n = q;
807 } while (n != 0);
808 WCMD_strrev (buff);
809 return buff;
812 /*****************************************************************************
813 * WCMD_strrev
815 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
818 WCHAR * WCMD_strrev (WCHAR *buff) {
820 int r, i;
821 WCHAR b;
823 r = strlenW (buff);
824 for (i=0; i<r/2; i++) {
825 b = buff[i];
826 buff[i] = buff[r-i-1];
827 buff[r-i-1] = b;
829 return (buff);
833 /*****************************************************************************
834 * WCMD_dir_sort
836 * Sort based on the /O options supplied on the command line
838 int WCMD_dir_sort (const void *a, const void *b)
840 WIN32_FIND_DATA *filea = (WIN32_FIND_DATA *)a;
841 WIN32_FIND_DATA *fileb = (WIN32_FIND_DATA *)b;
842 int result = 0;
844 /* If /OG or /O-G supplied, dirs go at the top or bottom, ignoring the
845 requested sort order for the directory components */
846 if (orderGroupDirs &&
847 ((filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ||
848 (fileb->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
850 BOOL aDir = filea->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
851 if (aDir) result = -1;
852 else result = 1;
853 if (orderGroupDirsReverse) result = -result;
854 return result;
856 /* Order by Name: */
857 } else if (dirOrder == Name) {
858 result = lstrcmpiW(filea->cFileName, fileb->cFileName);
860 /* Order by Size: */
861 } else if (dirOrder == Size) {
862 ULONG64 sizea = (((ULONG64)filea->nFileSizeHigh) << 32) + filea->nFileSizeLow;
863 ULONG64 sizeb = (((ULONG64)fileb->nFileSizeHigh) << 32) + fileb->nFileSizeLow;
864 if( sizea < sizeb ) result = -1;
865 else if( sizea == sizeb ) result = 0;
866 else result = 1;
868 /* Order by Date: (Takes into account which date (/T option) */
869 } else if (dirOrder == Date) {
871 FILETIME *ft;
872 ULONG64 timea, timeb;
874 if (dirTime == Written) {
875 ft = &filea->ftLastWriteTime;
876 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
877 ft = &fileb->ftLastWriteTime;
878 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
879 } else if (dirTime == Access) {
880 ft = &filea->ftLastAccessTime;
881 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
882 ft = &fileb->ftLastAccessTime;
883 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
884 } else {
885 ft = &filea->ftCreationTime;
886 timea = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
887 ft = &fileb->ftCreationTime;
888 timeb = (((ULONG64)ft->dwHighDateTime) << 32) + ft->dwLowDateTime;
890 if( timea < timeb ) result = -1;
891 else if( timea == timeb ) result = 0;
892 else result = 1;
894 /* Order by Extension: (Takes into account which date (/T option) */
895 } else if (dirOrder == Extension) {
896 WCHAR drive[10];
897 WCHAR dir[MAX_PATH];
898 WCHAR fname[MAX_PATH];
899 WCHAR extA[MAX_PATH];
900 WCHAR extB[MAX_PATH];
902 /* Split into components */
903 WCMD_splitpath(filea->cFileName, drive, dir, fname, extA);
904 WCMD_splitpath(fileb->cFileName, drive, dir, fname, extB);
905 result = lstrcmpiW(extA, extB);
908 if (orderReverse) result = -result;
909 return result;
912 /*****************************************************************************
913 * WCMD_getfileowner
915 * Reverse a WCHARacter string in-place (strrev() is not available under unixen :-( ).
917 void WCMD_getfileowner(WCHAR *filename, WCHAR *owner, int ownerlen) {
919 ULONG sizeNeeded = 0;
920 DWORD rc;
921 WCHAR name[MAXSTRING];
922 WCHAR domain[MAXSTRING];
924 /* In case of error, return empty string */
925 *owner = 0x00;
927 /* Find out how much space we need for the owner security descritpor */
928 GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, 0, 0, &sizeNeeded);
929 rc = GetLastError();
931 if(rc == ERROR_INSUFFICIENT_BUFFER && sizeNeeded > 0) {
933 LPBYTE secBuffer;
934 PSID pSID = NULL;
935 BOOL defaulted = FALSE;
936 ULONG nameLen = MAXSTRING;
937 ULONG domainLen = MAXSTRING;
938 SID_NAME_USE nameuse;
940 secBuffer = (LPBYTE) HeapAlloc(GetProcessHeap(),0,sizeNeeded * sizeof(BYTE));
941 if(!secBuffer) return;
943 /* Get the owners security descriptor */
944 if(!GetFileSecurity(filename, OWNER_SECURITY_INFORMATION, secBuffer,
945 sizeNeeded, &sizeNeeded)) {
946 HeapFree(GetProcessHeap(),0,secBuffer);
947 return;
950 /* Get the SID from the SD */
951 if(!GetSecurityDescriptorOwner(secBuffer, &pSID, &defaulted)) {
952 HeapFree(GetProcessHeap(),0,secBuffer);
953 return;
956 /* Convert to a username */
957 if (LookupAccountSid(NULL, pSID, name, &nameLen, domain, &domainLen, &nameuse)) {
958 static const WCHAR fmt[] = {'%','s','%','c','%','s','\0'};
959 snprintfW(owner, ownerlen, fmt, domain, '\\', name);
961 HeapFree(GetProcessHeap(),0,secBuffer);
963 return;
966 /*****************************************************************************
967 * WCMD_dir_trailer
969 * Print out the trailer for the supplied drive letter
971 static void WCMD_dir_trailer(WCHAR drive) {
972 ULARGE_INTEGER avail, total, freebytes;
973 DWORD status;
974 WCHAR driveName[4] = {'c',':','\\','\0'};
976 driveName[0] = drive;
977 status = GetDiskFreeSpaceEx (driveName, &avail, &total, &freebytes);
978 WINE_TRACE("Writing trailer for '%s' gave %d(%d)\n", wine_dbgstr_w(driveName),
979 status, GetLastError());
981 if (errorlevel==0 && !bare) {
982 if (recurse) {
983 static const WCHAR fmt1[] = {'\n',' ',' ',' ',' ',' ','T','o','t','a','l',' ','f','i','l','e','s',
984 ' ','l','i','s','t','e','d',':','\n','%','8','d',' ','f','i','l','e',
985 's','%','2','5','s',' ','b','y','t','e','s','\n','\0'};
986 static const WCHAR fmt2[] = {'%','8','d',' ','d','i','r','e','c','t','o','r','i','e','s',' ','%',
987 '1','8','s',' ','b','y','t','e','s',' ','f','r','e','e','\n','\n',
988 '\0'};
989 WCMD_output (fmt1, file_total, WCMD_filesize64 (byte_total));
990 WCMD_output (fmt2, dir_total, WCMD_filesize64 (freebytes.QuadPart));
991 } else {
992 static const WCHAR fmt[] = {' ','%','1','8','s',' ','b','y','t','e','s',' ','f','r','e','e',
993 '\n','\n','\0'};
994 WCMD_output (fmt, WCMD_filesize64 (freebytes.QuadPart));