Subversion Repositories SvarDOS

Rev

Rev 2037 | Rev 2039 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2019 mateusz.vi 1
/****************************************************************************
2
 
3
  TREE - Graphically displays the directory structure of a drive or path
4
 
5
****************************************************************************/
6
 
7
#define VERSION "1.04"
8
 
9
/****************************************************************************
10
 
11
  Written by: Kenneth J. Davis
12
  Date:       August, 2000
13
  Updated:    September, 2000; October, 2000; November, 2000; January, 2001;
14
              May, 2004; Sept, 2005
15
  Contact:    jeremyd@computer.org
16
 
17
 
18
Copyright (c): Public Domain [United States Definition]
19
 
20
Permission is hereby granted, free of charge, to any person obtaining a copy
21
of this software and associated documentation files (the "Software"), to deal
22
in the Software without restriction, including without limitation the rights
23
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
24
copies of the Software, and to permit persons to whom the Software is
25
furnished to do so, subject to the following conditions:
26
 
27
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
29
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR AUTHORS BE
31
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
32
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
33
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
34
DEALINGS IN THE SOFTWARE.
35
 
36
****************************************************************************/
37
 
38
 
39
/* Include files */
2034 mateusz.vi 40
#include <dos.h>
2019 mateusz.vi 41
#include <stdlib.h>
42
#include <stdio.h>
43
#include <string.h>
44
#include <direct.h>
45
#include <ctype.h>
46
#include <limits.h>
47
 
48
#include "stack.h"
49
 
2035 mateusz.vi 50
/* DOS disk accesses */
51
#include "dosdisk.h"
2019 mateusz.vi 52
 
53
 
54
/* Define getdrive so it returns current drive, 0=A,1=B,...           */
55
#define getdrive() getdisk()
56
 
57
#include <conio.h>  /* for getch()   */
58
 
59
 
60
/* The default extended forms of the lines used. */
61
#define VERTBAR_STR  "\xB3   "                 /* |    */
62
#define TBAR_HORZBAR_STR "\xC3\xC4\xC4\xC4"    /* +--- */
63
#define CBAR_HORZBAR_STR "\xC0\xC4\xC4\xC4"    /* \--- */
64
 
65
/* Global flags */
66
#define SHOWFILESON    1  /* Display names of files in directories       */
67
#define SHOWFILESOFF   0  /* Don't display names of files in directories */
68
 
69
#define ASCIICHARS     1  /* Use ASCII [7bit] characters                 */
70
#define EXTENDEDCHARS  0  /* Use extended ASCII [8bit] characters        */
71
 
72
#define NOPAUSE        0  /* Default, don't pause after screenfull       */
73
#define PAUSE          1  /* Wait for keypress after each page           */
74
 
75
 
76
/* Global variables */
77
short showFiles = SHOWFILESOFF;
78
short charSet = EXTENDEDCHARS;
79
short pause = NOPAUSE;
80
 
81
short dspAll = 0;  /* if nonzero includes HIDDEN & SYSTEM files in output */
82
short dspSize = 0; /* if nonzero displays filesizes                       */
83
short dspAttr = 0; /* if nonzero displays file attributes [DACESHRBP]     */
84
short dspSumDirs = 0; /* show count of subdirectories  (per dir and total)*/
85
 
86
 
87
/* maintains total count, for > 4billion dirs, use a __int64 */
88
unsigned long totalSubDirCnt = 0;
89
 
90
 
91
/* text window size, used to determine when to pause,
92
   Note: rows is total rows available - 2
2022 mateusz.vi 93
   1 is for pause message and then one to prevent auto scroll up
2019 mateusz.vi 94
*/
95
short cols=80, rows=23;   /* determined these on startup (when possible)  */
96
 
97
 
98
 
99
/* Global constants */
100
#define SERIALLEN 16      /* Defines max size of volume & serial number   */
101
#define VOLLEN 128
102
 
103
#define MAXBUF 1024       /* Must be larger than max file path length     */
104
char path[MAXBUF];        /* Path to begin search from, default=current   */
105
 
106
#define MAXPADLEN (MAXBUF*2) /* Must be large enough to hold the maximum padding */
107
/* (MAXBUF/2)*4 == (max path len / min 2chars dirs "?\") * 4chars per padding    */
108
 
109
/* The maximum size any line of text output can be, including room for '\0'*/
110
#define MAXLINE 160        /* Increased to fit two lines for translations  */
111
 
112
 
113
/* The hard coded strings used by the following show functions.            */
114
 
115
/* common to many functions [Set 1] */
116
char newLine[MAXLINE] = "\n";
117
 
118
/* showUsage [Set 2] - Each %c will be replaced with proper switch/option */
119
char treeDescription[MAXLINE] = "Graphically displays the directory structure of a drive or path.\n";
120
char treeUsage[MAXLINE] =       "TREE [drive:][path] [%c%c] [%c%c]\n";
121
char treeFOption[MAXLINE] =     "   %c%c   Display the names of the files in each directory.\n";
122
char treeAOption[MAXLINE] =     "   %c%c   Use ASCII instead of extended characters.\n";
123
 
124
/* showInvalidUsage [Set 3] */
125
char invalidOption[MAXLINE] = "Invalid switch - %s\n";  /* Must include the %s for option given. */
126
char useTreeHelp[MAXLINE] =   "Use TREE %c? for usage information.\n"; /* %c replaced with switch */
127
 
128
/* showVersionInfo [Set 4] */
129
/* also uses treeDescription */
130
char treeGoal[MAXLINE] =      "Written to work with FreeDOS\n";
131
char treePlatforms[MAXLINE] = "Win32(c) console and DOS with LFN support.\n";
132
char version[MAXLINE] =       "Version %s\n"; /* Must include the %s for version string. */
133
char writtenBy[MAXLINE] =     "Written by: Kenneth J. Davis\n";
134
char writtenDate[MAXLINE] =   "Date:       2000, 2001, 2004\n";
135
char contact[MAXLINE] =       "Contact:    jeremyd@computer.org\n";
136
char copyright[MAXLINE] =     "Copyright (c): Public Domain [United States Definition]\n";
137
 
138
/* showInvalidDrive [Set 5] */
139
char invalidDrive[MAXLINE] = "Invalid drive specification\n";
140
 
141
/* showInvalidPath [Set 6] */
142
char invalidPath[MAXLINE] = "Invalid path - %s\n"; /* Must include %s for the invalid path given. */
143
 
144
/* Misc Error messages [Set 7] */
145
/* showBufferOverrun */
146
/* %u required to show what the buffer's current size is. */
147
char bufferToSmall[MAXLINE] = "Error: File path specified exceeds maximum buffer = %u bytes\n";
148
/* showOutOfMemory */
149
/* %s required to display what directory we were processing when ran out of memory. */
150
char outOfMemory[MAXLINE] = "Out of memory on subdirectory: %s\n";
151
 
152
/* main [Set 1] */
153
char pathListingNoLabel[MAXLINE] = "Directory PATH listing\n";
154
char pathListingWithLabel[MAXLINE] = "Directory PATH listing for Volume %s\n"; /* %s for label */
155
char serialNumber[MAXLINE] = "Volume serial number is %s\n"; /* Must include %s for serial #   */
156
char noSubDirs[MAXLINE] = "No subdirectories exist\n\n";
157
char pauseMsg[MAXLINE]  = " --- Press any key to continue ---\n";
158
 
159
/* Option Processing - parseArguments [Set 8]      */
160
char optionchar1 = '/';  /* Primary character used to determine option follows  */
161
char optionchar2 = '-';  /* Secondary character used to determine option follows  */
162
const char OptShowFiles[2] = { 'F', 'f' };  /* Show files */
163
const char OptUseASCII[2]  = { 'A', 'a' };  /* Use ASCII only */
164
const char OptVersion[2]   = { 'V', 'v' };  /* Version information */
165
const char OptSFNs[2]      = { 'S', 's' };  /* Shortnames only (disable LFN support) */
166
const char OptPause[2]     = { 'P', 'p' };  /* Pause after each page (screenfull) */
167
const char OptDisplay[2]   = { 'D', 'd' };  /* modify Display settings */
168
const char OptSort[2]      = { 'O', 'o' };  /* sort Output */
169
 
170
 
171
/* Procedures */
172
 
173
 
2034 mateusz.vi 174
#define FILE_TYPE_UNKNOWN 0x00
175
#define FILE_TYPE_DISK    0x01
176
#define FILE_TYPE_CHAR    0x02
177
#define FILE_TYPE_PIPE    0x03
178
#define FILE_TYPE_REMOTE  0x80
179
 
180
/* Returns file type of stdout.
181
 * Output, one of predefined values above indicating if
182
 *         handle refers to file (FILE_TYPE_DISK), a
183
 *         device such as CON (FILE_TYPE_CHAR), a
184
 *         pipe (FILE_TYPE_PIPE), or unknown.
185
 * On errors or unspecified input, FILE_TYPE_UNKNOWN
186
 * is returned. */
187
static unsigned char GetStdoutType(void) {
188
  union REGS r;
189
 
190
  r.x.ax = 0x4400;                 /* DOS 2+, IOCTL Get Device Info */
191
  r.x.bx = 0x0001;                 /* file handle (stdout) */
192
 
193
  /* We assume hFile is an opened DOS handle, & if invalid call should fail. */
194
  intdos(&r, &r);     /* Clib function to invoke DOS int21h call   */
195
 
196
  /* error? */
197
  if (r.x.cflag != 0) return(FILE_TYPE_UNKNOWN);
198
 
199
  /* if bit 7 is set it is a char dev */
200
  if (r.x.dx & 0x80) return(FILE_TYPE_CHAR);
201
 
202
  /* file is remote */
203
  if (r.x.dx & 0x8000) return(FILE_TYPE_REMOTE);
204
 
205
  /* assume valid file handle */
206
  return(FILE_TYPE_DISK);
207
}
208
 
209
 
2019 mateusz.vi 210
/* sets rows & cols to size of actual console window
211
 * force NOPAUSE if appears output redirected to a file or
212
 * piped to another program
213
 * Uses hard coded defaults and leaves pause flag unchanged
214
 * if unable to obtain information.
215
 */
2034 mateusz.vi 216
static void getConsoleSize(void) {
217
  unsigned short far *bios_cols = (unsigned short far *)MK_FP(0x40,0x4A);
218
  unsigned short far *bios_size = (unsigned short far *)MK_FP(0x40,0x4C);
2019 mateusz.vi 219
 
2034 mateusz.vi 220
  switch (GetStdoutType()) {
221
    case FILE_TYPE_DISK: /* e.g. redirected to a file, tree > filelist.txt */
222
      /* Output to a file or program, so no screen to fill (no max cols or rows) */
223
      pause = NOPAUSE;   /* so ignore request to pause */
224
      break;
225
    case FILE_TYPE_CHAR:  /* e.g. the console */
226
    case FILE_TYPE_UNKNOWN:  /* else at least attempt to get proper limits */
227
    case FILE_TYPE_REMOTE:
228
    default:
229
      if ((*bios_cols == 0) || (*bios_size == 0)) { /* MDA does not report size */
230
        cols = 80;
231
        rows = 23;
232
      } else {
233
        cols = *bios_cols;
234
        rows = *bios_size / cols / 2;
235
        if (rows > 2) rows -= 2; /* necessary to keep screen from scrolling */
2019 mateusz.vi 236
      }
2034 mateusz.vi 237
      break;
2019 mateusz.vi 238
  }
239
}
240
 
2034 mateusz.vi 241
 
242
/* retrieve attributes (ReadOnly/System/...) about file or directory
243
 * returns (DWORD)-1 on error
244
 */
245
static DWORD GetFileAttributes(const char *pathname) {
246
  union REGS r;
247
  struct SREGS s;
248
  char buffer[260];
249
  int slen;
250
 
251
  /* 1st try LFN - Extended get/set attributes (in case LFN used) */
252
  if (LFN_Enable_Flag)
253
  {
254
    r.x.ax = 0x7143;                  /* LFN API, Extended Get/Set Attributes */
255
    r.x.bx = 0x00;                    /* BL=0, get file attributes            */
256
    r.x.dx = FP_OFF(pathname);        /* DS:DX points to ASCIIZ filename      */
257
 
258
    segread(&s);                      /* load with current segment values     */
259
    s.ds = FP_SEG(pathname);          /* get Segment of our filename pointer  */
260
 
261
    r.x.cflag = 1;                    /* should be set when unsupported ***   */
262
    asm stc;                          /* but clib usually ignores on entry    */
263
 
264
    /* Actually perform the call, carry should be set on error or unuspported */
265
    intdosx(&r, &r, &s);         /* Clib function to invoke DOS int21h call   */
266
 
267
    if (!r.x.cflag)              /* if carry not set then cx has desired info */
268
      return (DWORD)r.x.cx;
269
    /* else error other than unsupported LFN api or invalid function [FreeDOS]*/
270
    else if ((r.x.ax != 0x7100) || (r.x.ax != 0x01))
271
      return (DWORD)-1;
272
    /* else fall through to standard get/set file attribute call */
273
  }
274
 
275
  /* we must remove any slashes from end */
276
  slen = strlen(pathname) - 1;  /* Warning, assuming pathname is not ""   */
277
  strcpy(buffer, pathname);
278
  if ((buffer[slen] == '\\') || (buffer[slen] == '/')) /* ends in a slash */
279
  {
280
    /* don't remove from root directory (slen == 0),
281
     * ignore UNC paths as SFN doesn't handle them anyway
282
     * if slen == 2, then check if drive given (e.g. C:\)
283
     */
284
    if (slen && !(slen == 2 &&  buffer[1] == ':'))
285
      buffer[slen] = '\0';
286
  }
287
  /* return standard attributes */
288
  r.x.ax = 0x4300;                  /* standard Get/Set File Attributes */
289
  r.x.dx = FP_OFF(buffer);          /* DS:DX points to ASCIIZ filename      */
290
  segread(&s);                      /* load with current segment values     */
291
  s.ds = FP_SEG(buffer);            /* get Segment of our filename pointer  */
292
  intdosx(&r, &r, &s);              /* invoke the DOS int21h call           */
293
 
294
  //if (r.x.cflag) printf("ERROR getting std attributes of %s, DOS err %i\n", buffer, r.x.ax);
295
  if (r.x.cflag) return (DWORD)-1;  /* error obtaining attributes           */
296
  return (DWORD)(0x3F & r.x.cx); /* mask off any DRDOS bits     */
297
}
298
 
299
 
2019 mateusz.vi 300
/* when pause == NOPAUSE then identical to printf,
301
   otherwise counts lines printed and pauses as needed.
302
   Should be used for all messages printed that do not
303
   immediately exit afterwards (else printf may be used).
304
   May display N too many lines before pause if line is
305
   printed that exceeds cols [N=linelen%cols] and lacks
306
   any newlines (but this should not occur in tree).
307
*/
308
#include <stdarg.h>  /* va_list, va_start, va_end */
2037 mateusz.vi 309
static int pprintf(const char *msg, ...) {
2030 mateusz.vi 310
  static int lineCnt = -1;
2019 mateusz.vi 311
  static int lineCol = 0;
312
  va_list argptr;
313
  int cnt;
314
  char buffer[MAXBUF];
315
 
2030 mateusz.vi 316
  if (lineCnt == -1) lineCnt = rows;
317
 
2019 mateusz.vi 318
  va_start(argptr, msg);
319
  cnt = vsprintf(buffer, msg, argptr);
320
  va_end(argptr);
321
 
322
  if (pause == PAUSE)
323
  {
2030 mateusz.vi 324
    char *l = buffer;
325
    char *t;
2019 mateusz.vi 326
    /* cycle through counting newlines and lines > cols */
2030 mateusz.vi 327
    for (t = strchr(l, '\n'); t != NULL; t = strchr(l, '\n'))
2019 mateusz.vi 328
    {
2030 mateusz.vi 329
      char c;
2019 mateusz.vi 330
      t++;             /* point to character after newline */
2030 mateusz.vi 331
      c = *t;          /* store current value */
2019 mateusz.vi 332
      *t = '\0';       /* mark as end of string */
333
 
334
      /* print all but last line of a string that wraps across rows */
335
      /* adjusting for partial lines printed without the newlines   */
336
      while (strlen(l)+lineCol > cols)
337
      {
338
        char c = l[cols-lineCol];
339
        l[cols-lineCol] = '\0';
340
        printf("%s", l);
341
        l[cols-lineCol] = c;
342
        l += cols-lineCol;
343
 
344
        lineCnt--;  lineCol = 0;
345
        if (!lineCnt) { lineCnt= rows;  fflush(NULL);  fprintf(stderr, "%s", pauseMsg);  getch(); }
346
      }
347
 
348
      printf("%s", l); /* print out this line */
349
      *t = c;          /* restore value */
350
      l = t;           /* mark beginning of next line */
351
 
352
      lineCnt--;  lineCol = 0;
353
      if (!lineCnt) { lineCnt= rows;  fflush(NULL);  fprintf(stderr, "%s", pauseMsg);  getch(); }
354
    }
355
    printf("%s", l);   /* print rest of string that lacks newline */
356
    lineCol = strlen(l);
357
  }
358
  else  /* NOPAUSE */
359
    printf("%s", buffer);
360
 
361
  return cnt;
362
}
363
 
364
 
365
/* Displays to user valid options then exits program indicating no error */
2037 mateusz.vi 366
static void showUsage(void) {
2019 mateusz.vi 367
  printf("%s%s%s%s", treeDescription, newLine, treeUsage, newLine);
368
  printf("%s%s%s", treeFOption, treeAOption, newLine);
369
  exit(1);
370
}
371
 
372
 
373
/* Displays error message then exits indicating error */
2037 mateusz.vi 374
static void showInvalidUsage(char * badOption) {
2019 mateusz.vi 375
  printf(invalidOption, badOption);
376
  printf("%s%s", useTreeHelp, newLine);
377
  exit(1);
378
}
379
 
380
 
381
/* Displays author, copyright, etc info, then exits indicating no error. */
2037 mateusz.vi 382
static void showVersionInfo(void) {
2019 mateusz.vi 383
  printf("%s%s%s%s%s", treeDescription, newLine, treeGoal, treePlatforms, newLine);
384
  printf(version, VERSION);
385
  printf("%s%s%s%s%s", writtenBy, writtenDate, contact, newLine, newLine);
386
  printf("%s%s", copyright, newLine);
387
  exit(1);
388
}
389
 
390
 
391
/* Displays error messge for invalid drives and exits */
2037 mateusz.vi 392
static void showInvalidDrive(void) {
2019 mateusz.vi 393
  printf(invalidDrive);
394
  exit(1);
395
}
396
 
397
 
398
/* Takes a fullpath, splits into drive (C:, or \\server\share) and path */
2037 mateusz.vi 399
static void splitpath(char *fullpath, char *drive, char *path);
2019 mateusz.vi 400
 
401
/**
402
 * Takes a given path, strips any \ or / that may appear on the end.
403
 * Returns a pointer to its static buffer containing path
404
 * without trailing slash and any necessary display conversions.
405
 */
2037 mateusz.vi 406
static char *fixPathForDisplay(char *path);
2019 mateusz.vi 407
 
408
/* Displays error message for invalid path; Does NOT exit */
2037 mateusz.vi 409
static void showInvalidPath(char *path) {
2019 mateusz.vi 410
  char partialPath[MAXBUF], dummy[MAXBUF];
411
 
412
  pprintf("%s\n", path);
413
  splitpath(path, dummy, partialPath);
414
  pprintf(invalidPath, fixPathForDisplay(partialPath));
415
}
416
 
417
/* Displays error message for out of memory; Does NOT exit */
2037 mateusz.vi 418
static void showOutOfMemory(char *path) {
2019 mateusz.vi 419
  pprintf(outOfMemory, path);
420
}
421
 
422
/* Displays buffer exceeded message and exits */
2037 mateusz.vi 423
static void showBufferOverrun(WORD maxSize) {
2019 mateusz.vi 424
  printf(bufferToSmall, maxSize);
425
  exit(1);
426
}
427
 
428
 
429
/**
430
 * Takes a fullpath, splits into drive (C:, or \\server\share) and path
431
 * It assumes a colon as the 2nd character means drive specified,
432
 * a double slash \\ (\\, //, \/, or /\) specifies network share.
433
 * If neither drive nor network share, then assumes whole fullpath
434
 * is path, and sets drive to "".
435
 * If drive specified, then set drive to it and colon, eg "C:", with
436
 * the rest of fullpath being set in path.
437
 * If network share, the slash slash followed by the server name,
438
 * another slash and either the rest of fullpath or up to, but not
439
 * including, the next slash are placed in drive, eg "\\KJD\myshare";
440
 * the rest of the fullpath including the slash are placed in
441
 * path, eg "\mysubdir"; where fullpath is "\\KJD\myshare\mysubdir".
442
 * None of these may be NULL, and drive and path must be large
443
 * enough to hold fullpath.
444
 */
2037 mateusz.vi 445
static void splitpath(char *fullpath, char *drive, char *path) {
2027 mateusz.vi 446
  char *src = fullpath;
447
  char oldchar;
2019 mateusz.vi 448
 
449
  /* If either network share or path only starting at root directory */
450
  if ( (*src == '\\') || (*src == '/') )
451
  {
452
    src++;
453
 
454
    if ( (*src == '\\') || (*src == '/') ) /* network share */
455
    {
456
      src++;
457
 
458
      /* skip past server name */
459
      while ( (*src != '\\') && (*src != '/') && (*src != '\0') )
460
        src++;
461
 
462
      /* skip past slash (\ or /) separating  server from share */
463
      if (*src != '\0') src++;
464
 
465
      /* skip past share name */
466
      while ( (*src != '\\') && (*src != '/') && (*src != '\0') )
467
        src++;
468
 
469
      /* src points to start of path, either a slash or '\0' */
470
      oldchar = *src;
471
      *src = '\0';
472
 
473
      /* copy server name to drive */
474
      strcpy(drive, fullpath);
475
 
476
      /* restore character used to mark end of server name */
477
      *src = oldchar;
478
 
479
      /* copy path */
480
      strcpy(path, src);
481
    }
482
    else /* path only starting at root directory */
483
    {
484
      /* no drive, so set path to same as fullpath */
485
      strcpy(drive, "");
486
      strcpy(path, fullpath);
487
    }
488
  }
489
  else
490
  {
491
    if (*src != '\0') src++;
492
 
493
    /* Either drive and path or path only */
494
    if (*src == ':')
495
    {
496
      /* copy drive specified */
497
      *drive = *fullpath;  drive++;
498
      *drive = ':';        drive++;
499
      *drive = '\0';
500
 
501
      /* copy path */
502
      src++;
503
      strcpy(path, src);
504
    }
505
    else
506
    {
507
      /* no drive, so set path to same as fullpath */
508
      strcpy(drive, "");
509
      strcpy(path, fullpath);
510
    }
511
  }
512
}
513
 
514
 
515
/* Converts given path to full path */
2037 mateusz.vi 516
static void getProperPath(char *fullpath) {
2019 mateusz.vi 517
  char drive[MAXBUF];
518
  char path[MAXBUF];
519
 
520
  splitpath(fullpath, drive, path);
521
 
522
  /* if no drive specified use current */
523
  if (drive[0] == '\0')
524
  {
525
    sprintf(fullpath, "%c:%s", 'A'+ getdrive(), path);
526
  }
527
  else if (path[0] == '\0') /* else if drive but no path specified */
528
  {
529
    if ((drive[0] == '\\') || (drive[0] == '/'))
530
    {
531
      /* if no path specified and network share, use root   */
532
      sprintf(fullpath, "%s%s", drive, "\\");
533
    }
534
    else
535
    {
536
      /* if no path specified and drive letter, use current path */
537
      sprintf(fullpath, "%s%s", drive, ".");
538
    }
539
  }
540
  /* else leave alone, it has both a drive and path specified */
541
}
542
 
543
 
544
/* Parses the command line and sets global variables. */
2037 mateusz.vi 545
static void parseArguments(int argc, char *argv[]) {
2027 mateusz.vi 546
  int i;     /* temp loop variable */
2019 mateusz.vi 547
 
548
  /* if no drive specified on command line, use current */
549
  sprintf(path, "%c:.", 'A'+ getdrive());
550
 
551
  for (i = 1; i < argc; i++)
552
  {
553
    /* Check if user is giving an option or drive/path */
554
    if ((argv[i][0] == optionchar1) || (argv[i][0] == optionchar2) )
555
    {
556
      /* check multi character options 1st */
557
      if ((argv[i][1] == OptDisplay[0]) || (argv[i][1] == OptDisplay[1]))
558
      {
559
        switch (argv[i][2] & 0xDF)
560
        {
561
          case 'A' :       /*  /DA  display attributes */
562
            dspAttr = 1;
563
            break;
564
          case 'F' :       /*  /DF  display filesizes  */
565
            dspSize = 1;
566
            break;
567
          case 'H' :       /*  /DH  display hidden & system files (normally not shown) */
568
            dspAll = 1;
569
            break;
570
          case 'R' :       /*  /DR  display results at end */
571
            dspSumDirs = 1;
572
            break;
573
          default:
574
            showInvalidUsage(argv[i]);
575
        }
576
      }
577
      else if ((argv[i][1] == OptSort[0]) || (argv[i][1] == OptSort[1]))
578
      {
579
#if 1  // not yet supported
580
        showInvalidUsage(argv[i]);
581
#else
582
        int reverse = (argv[i][3] == '-')?1:0;  /* invert sort if suffixed with - */
583
        switch (argv[i][2] & 0xDF)
584
        {
585
          case 'F' :       /*  /Of  sort by Filesize   */
586
            break;
587
          case 'N' :       /*  /On  sort by fileName   */
588
            break;
589
          case 'E' :       /*  /Oe  sort by Extension  */
590
            break;
591
          default:
592
            showInvalidUsage(argv[i]);
593
        }
594
#endif
595
      }
596
      else /* a 1 character option (or invalid) */
597
      {
598
        if (argv[i][2] != '\0')
599
          showInvalidUsage(argv[i]);
600
 
601
        /* Must check both uppercase and lowercase                        */
602
        if ((argv[i][1] == OptShowFiles[0]) || (argv[i][1] == OptShowFiles[1]))
603
          showFiles = SHOWFILESON; /* set file display flag appropriately */
604
        else if ((argv[i][1] == OptUseASCII[0]) || (argv[i][1] == OptUseASCII[1]))
605
          charSet = ASCIICHARS;    /* set charset flag appropriately      */
606
        else if (argv[i][1] == '?')
607
          showUsage();             /* show usage info and exit            */
608
        else if ((argv[i][1] == OptVersion[0]) || (argv[i][1] == OptVersion[1]))
609
          showVersionInfo();       /* show version info and exit          */
610
        else if ((argv[i][1] == OptSFNs[0]) || (argv[i][1] == OptSFNs[1]))
611
          LFN_Enable_Flag = LFN_DISABLE;         /* force shortnames only */
612
        else if ((argv[i][1] == OptPause[0]) || (argv[i][1] == OptPause[1]))
613
          pause = PAUSE;     /* wait for keypress after each page (pause) */
614
        else /* Invalid or unknown option */
615
          showInvalidUsage(argv[i]);
616
      }
617
    }
618
    else /* should be a drive/path */
619
    {
2030 mateusz.vi 620
      char *dptr = path;
621
      char *cptr;
2019 mateusz.vi 622
 
2030 mateusz.vi 623
      if (strlen(argv[i]) > MAXBUF) showBufferOverrun(MAXBUF);
624
 
2019 mateusz.vi 625
      /* copy path over, making all caps to look prettier, can be strcpy */
2030 mateusz.vi 626
      for (cptr = argv[i]; *cptr != '\0'; cptr++, dptr++) {
2019 mateusz.vi 627
        *dptr = toupper(*cptr);
2030 mateusz.vi 628
      }
2019 mateusz.vi 629
      *dptr = '\0';
630
 
631
      /* Converts given path to full path */
632
      getProperPath(path);
633
    }
634
  }
635
}
636
 
637
 
638
/**
639
 * Fills in the serial and volume variables with the serial #
640
 * and volume found using path.
2022 mateusz.vi 641
 * If there is an error getting the volume & serial#, then an
2019 mateusz.vi 642
 * error message is displayed and the program exits.
643
 * Volume and/or serial # returned may be blank if the path specified
2022 mateusz.vi 644
 * does not contain them, or an error retrieving
2019 mateusz.vi 645
 * (ie UNC paths under DOS), but path is valid.
646
 */
2037 mateusz.vi 647
static void GetVolumeAndSerial(char *volume, char *serial, char *path) {
2019 mateusz.vi 648
  char rootPath[MAXBUF];
649
  char dummy[MAXBUF];
650
  union serialNumber {
651
    DWORD serialFull;
652
    struct {
653
      WORD a;
654
      WORD b;
655
    } serialParts;
656
  } serialNum;
657
 
658
  /* get drive letter or share server\name */
659
  splitpath(path, rootPath, dummy);
660
  strcat(rootPath, "\\");
661
 
662
  if (GetVolumeInformation(rootPath, volume, VOLLEN,
663
      &serialNum.serialFull, NULL, NULL, NULL, 0) == 0)
664
	showInvalidDrive();
665
 
666
  if (serialNum.serialFull == 0)
667
    serial[0] = '\0';
668
  else
669
    sprintf(serial, "%04X:%04X",
670
      serialNum.serialParts.b, serialNum.serialParts.a);
671
}
672
 
673
 
674
#ifndef STDCALL
675
#define STDCALL __stdcall
676
#endif
677
 
678
 
679
/**
680
 * Stores directory information obtained from FindFirst/Next that
681
 * we may wish to make use of when displaying directory entry.
682
 * e.g. attribute, dates, etc.
683
 */
684
typedef struct DIRDATA
685
{
686
  DWORD subdirCnt;          /* how many subdirectories we have */
687
  DWORD fileCnt;            /* how many [normal] files we have */
688
  DWORD dwDirAttributes;    /* Directory attributes            */
689
} DIRDATA;
690
 
691
/**
692
 * Contains the information stored in a Stack necessary to allow
693
 * non-recursive function to display directory tree.
694
 */
695
typedef struct SUBDIRINFO
696
{
697
  struct SUBDIRINFO * parent; /* points to parent subdirectory                */
698
  char *currentpath;    /* Stores the full path this structure represents     */
699
  char *subdir;         /* points to last subdir within currentpath           */
700
  char *dsubdir;        /* Stores a display ready directory name              */
701
  long subdircnt;       /* Initially a count of how many subdirs in this dir  */
702
  HANDLE findnexthnd;   /* The handle returned by findfirst, used in findnext */
703
  struct DIRDATA ddata; /* Maintain directory information, eg attributes      */
704
} SUBDIRINFO;
705
 
706
 
707
/**
708
 * Returns 0 if no subdirectories, count if has subdirs.
709
 * Path must end in slash \ or /
710
 * On error (invalid path) displays message and returns -1L.
711
 * Stores additional directory data in ddata if non-NULL
712
 * and path is valid.
713
 */
2037 mateusz.vi 714
static long hasSubdirectories(char *path, DIRDATA *ddata) {
2019 mateusz.vi 715
  static WIN32_FIND_DATA findData;
716
  HANDLE hnd;
717
  static char buffer[MAXBUF];
718
  int hasSubdirs = 0;
719
 
720
  /* get the handle to start with (using wildcard spec) */
721
  strcpy(buffer, path);
722
  strcat(buffer, "*");
723
 
724
  /* Use FindFirstFileEx when available (falls back to FindFirstFile).
725
   * Allows us to limit returned results to just directories
726
   * if supported by underlying filesystem.
727
   */
2030 mateusz.vi 728
  hnd = FindFirstFileA(buffer, &findData);
2019 mateusz.vi 729
  if (hnd == INVALID_HANDLE_VALUE)
730
  {
731
    showInvalidPath(path); /* Display error message */
732
    return -1L;
733
  }
734
 
735
 
736
  /*  cycle through entries counting directories found until no more entries */
737
  do {
738
    if (((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) &&
739
	((findData.dwFileAttributes &
740
	 (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) == 0 || dspAll) )
741
    {
742
      if ( (strcmp(findData.cFileName, ".") != 0) && /* ignore initial [current] path */
743
           (strcmp(findData.cFileName, "..") != 0) ) /* and ignore parent path */
744
        hasSubdirs++;      /* subdir of initial path found, so increment counter */
745
    }
746
  } while(FindNextFile(hnd, &findData) != 0);
747
 
748
  /* prevent resource leaks, close the handle. */
749
  FindClose(hnd);
750
 
751
  if (ddata != NULL)  // don't bother if user doesn't want them
752
  {
753
    /* The root directory of a volume (including non root paths
754
       corresponding to mount points) may not have a current (.) and
755
       parent (..) entry.  So we can't get attributes for initial
2022 mateusz.vi 756
       path in above loop from the FindFile call as it may not show up
2019 mateusz.vi 757
       (no . entry).  So instead we explicitly get them here.
758
    */
759
    if ((ddata->dwDirAttributes = GetFileAttributes(path)) == (DWORD)-1)
760
    {
761
      //printf("ERROR: unable to get file attr, %i\n", GetLastError());
762
      ddata->dwDirAttributes = 0;
763
    }
764
 
765
    /* a curiosity, for showing sum of directories process */
766
    ddata->subdirCnt = hasSubdirs;
767
  }
768
  totalSubDirCnt += hasSubdirs;
769
 
770
  return hasSubdirs;
771
}
772
 
773
 
774
/**
775
 * Allocates memory and stores the necessary stuff to allow us to
776
 * come back to this subdirectory after handling its subdirectories.
777
 * parentpath must end in \ or / or be NULL, however
778
 * parent should only be NULL for initialpath
779
 * if subdir does not end in slash, one is added to stored subdir
780
 * dsubdir is subdir already modified so ready to display to user
781
 */
2037 mateusz.vi 782
static SUBDIRINFO *newSubdirInfo(SUBDIRINFO *parent, char *subdir, char *dsubdir) {
2027 mateusz.vi 783
  int parentLen, subdirLen;
2032 mateusz.vi 784
  SUBDIRINFO *temp;
2019 mateusz.vi 785
 
786
  /* Get length of parent directory */
787
  if (parent == NULL)
788
    parentLen = 0;
789
  else
790
    parentLen = strlen(parent->currentpath);
791
 
792
  /* Get length of subdir, add 1 if does not end in slash */
793
  subdirLen = strlen(subdir);
794
  if ((subdirLen < 1) || ( (*(subdir+subdirLen-1) != '\\') && (*(subdir+subdirLen-1) != '/') ) )
795
    subdirLen++;
796
 
2032 mateusz.vi 797
  temp = (SUBDIRINFO *)malloc(sizeof(SUBDIRINFO));
2022 mateusz.vi 798
  if (temp == NULL)
2019 mateusz.vi 799
  {
800
    showOutOfMemory(subdir);
801
    return NULL;
802
  }
803
  if ( ((temp->currentpath = (char *)malloc(parentLen+subdirLen+1)) == NULL) ||
804
       ((temp->dsubdir = (char *)malloc(strlen(dsubdir)+1)) == NULL) )
805
  {
806
    showOutOfMemory(subdir);
807
    if (temp->currentpath != NULL) free(temp->currentpath);
808
    free(temp);
809
    return NULL;
810
  }
811
  temp->parent = parent;
812
  if (parent == NULL)
813
    strcpy(temp->currentpath, "");
814
  else
815
    strcpy(temp->currentpath, parent->currentpath);
816
  strcat(temp->currentpath, subdir);
817
  /* if subdir[subdirLen-1] == '\0' then we must append a slash */
818
  if (*(subdir+subdirLen-1) == '\0')
819
    strcat(temp->currentpath, "\\");
820
  temp->subdir = temp->currentpath+parentLen;
821
  strcpy(temp->dsubdir, dsubdir);
822
  if ((temp->subdircnt = hasSubdirectories(temp->currentpath, &(temp->ddata))) == -1L)
823
  {
824
    free (temp->currentpath);
825
    free (temp->dsubdir);
826
    free(temp);
827
    return NULL;
828
  }
829
  temp->findnexthnd = INVALID_HANDLE_VALUE;
830
 
831
  return temp;
832
}
833
 
834
/**
835
 * Extends the padding with the necessary 4 characters.
836
 * Returns the pointer to the padding.
2022 mateusz.vi 837
 * padding should be large enough to hold the additional
2019 mateusz.vi 838
 * characters and '\0', moreSubdirsFollow specifies if
839
 * this is the last subdirectory in a given directory
840
 * or if more follow (hence if a | is needed).
841
 * padding must not be NULL
842
 */
2037 mateusz.vi 843
static char * addPadding(char *padding, int moreSubdirsFollow) {
844
  if (moreSubdirsFollow) {
845
    /* 1st char is | or a vertical bar */
846
    if (charSet == EXTENDEDCHARS) {
847
      strcat(padding, VERTBAR_STR);
848
    } else {
849
      strcat(padding, "|   ");
2019 mateusz.vi 850
    }
2037 mateusz.vi 851
  } else {
852
    strcat(padding, "    ");
853
  }
2019 mateusz.vi 854
 
2037 mateusz.vi 855
  return(padding);
2019 mateusz.vi 856
}
857
 
858
/**
2025 mateusz.vi 859
 * Removes the last padding added (last 4 characters added).
860
 * Does nothing if less than 4 characters in string.
2019 mateusz.vi 861
 * padding must not be NULL
862
 * Returns the pointer to padding.
863
 */
2037 mateusz.vi 864
static char *removePadding(char *padding) {
2027 mateusz.vi 865
  size_t len = strlen(padding);
2019 mateusz.vi 866
 
2025 mateusz.vi 867
  if (len < 4) return padding;
868
  *(padding + len - 4) = '\0';
2019 mateusz.vi 869
 
870
  return padding;
871
}
872
 
873
/**
874
 * Takes a given path, strips any \ or / that may appear on the end.
875
 * Returns a pointer to its static buffer containing path
876
 * without trailing slash and any necessary display conversions.
877
 */
2037 mateusz.vi 878
static char *fixPathForDisplay(char *path) {
2019 mateusz.vi 879
  static char buffer[MAXBUF];
2027 mateusz.vi 880
  int pathlen;
2019 mateusz.vi 881
 
882
  strcpy(buffer, path);
883
  pathlen = strlen(buffer);
2037 mateusz.vi 884
  if (pathlen > 1) {
2019 mateusz.vi 885
    pathlen--;
2037 mateusz.vi 886
    if ((buffer[pathlen] == '\\') || (buffer[pathlen] == '/')) {
2019 mateusz.vi 887
      buffer[pathlen] = '\0'; // strip off trailing slash on end
2037 mateusz.vi 888
    }
2019 mateusz.vi 889
  }
890
 
891
  return buffer;
892
}
893
 
894
/**
895
 * Displays the current path, with necessary padding before it.
896
 * A \ or / on end of currentpath is not shown.
897
 * moreSubdirsFollow should be nonzero if this is not the last
898
 * subdirectory to be displayed in current directory, else 0.
899
 * Also displays additional information, such as attributes or
900
 * sum of size of included files.
901
 * currentpath is an ASCIIZ string of path to display
902
 *             assumed to be a displayable path (ie. OEM or UTF-8)
903
 * padding is an ASCIIZ string to display prior to entry.
904
 * moreSubdirsFollow is -1 for initial path else >= 0.
905
 */
2037 mateusz.vi 906
static void showCurrentPath(char *currentpath, char *padding, int moreSubdirsFollow, DIRDATA *ddata) {
2019 mateusz.vi 907
  if (padding != NULL)
908
    pprintf("%s", padding);
909
 
910
  /* print lead padding except for initial directory */
911
  if (moreSubdirsFollow >= 0)
912
  {
913
    if (charSet == EXTENDEDCHARS)
914
    {
915
      if (moreSubdirsFollow)
916
        pprintf("%s", TBAR_HORZBAR_STR);
917
      else
918
        pprintf("%s", CBAR_HORZBAR_STR);
2037 mateusz.vi 919
    } else {
2019 mateusz.vi 920
      if (moreSubdirsFollow)
921
        pprintf("+---");
922
      else
923
        pprintf("\\---");
924
    }
925
  }
926
 
927
  /* optional display data */
928
  if (dspAttr)  /* attributes */
2031 mateusz.vi 929
    pprintf("[%c%c%c%c%c] ",
2019 mateusz.vi 930
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_DIRECTORY)?'D':' ',  /* keep this one? its always true */
931
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_ARCHIVE)?'A':' ',
932
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_SYSTEM)?'S':' ',
933
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_HIDDEN)?'H':' ',
2031 mateusz.vi 934
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_READONLY)?'R':' '
2019 mateusz.vi 935
    );
936
 
937
  /* display directory name */
938
  pprintf("%s\n", currentpath);
939
}
940
 
941
 
2022 mateusz.vi 942
/**
2019 mateusz.vi 943
 * Displays summary information about directory.
944
 * Expects to be called after displayFiles (optionally called)
945
 */
2037 mateusz.vi 946
static void displaySummary(char *padding, int hasMoreSubdirs, DIRDATA *ddata) {
2019 mateusz.vi 947
  addPadding(padding, hasMoreSubdirs);
948
 
2037 mateusz.vi 949
  if (dspSumDirs) {
950
    if (showFiles == SHOWFILESON) {
2019 mateusz.vi 951
      /* print File summary with lead padding, add filesize to it */
952
      pprintf("%s%lu files\n", padding, ddata->fileCnt);
953
    }
954
 
955
    /* print Directory summary with lead padding */
956
    pprintf("%s%lu subdirectories\n", padding, ddata->subdirCnt);
957
 
958
    /* show [nearly] blank line after summary */
959
    pprintf("%s\n", padding);
960
  }
961
 
962
  removePadding(padding);
963
}
964
 
2022 mateusz.vi 965
/**
2019 mateusz.vi 966
 * Displays files in directory specified by path.
967
 * Path must end in slash \ or /
968
 * Returns -1 on error,
969
 *          0 if no files, but no errors either,
970
 *      or  1 if files displayed, no errors.
971
 */
2037 mateusz.vi 972
static int displayFiles(char *path, char *padding, int hasMoreSubdirs, DIRDATA *ddata) {
2019 mateusz.vi 973
  static char buffer[MAXBUF];
974
  WIN32_FIND_DATA entry; /* current directory entry info    */
975
  HANDLE dir;         /* Current directory entry working with      */
976
  unsigned long filesShown = 0;
977
 
978
  /* get handle for files in current directory (using wildcard spec) */
979
  strcpy(buffer, path);
980
  strcat(buffer, "*");
981
  dir = FindFirstFile(buffer, &entry);
982
  if (dir == INVALID_HANDLE_VALUE)
983
    return -1;
984
 
985
  addPadding(padding, hasMoreSubdirs);
986
 
987
  /* cycle through directory printing out files. */
2022 mateusz.vi 988
  do
2019 mateusz.vi 989
  {
990
    /* print padding followed by filename */
991
    if ( ((entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) &&
992
         ( ((entry.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN |
993
         FILE_ATTRIBUTE_SYSTEM)) == 0)  || dspAll) )
994
    {
995
      /* print lead padding */
996
      pprintf("%s", padding);
997
 
998
      /* optional display data */
999
      if (dspAttr)  /* file attributes */
2031 mateusz.vi 1000
        pprintf("[%c%c%c%c] ",
2019 mateusz.vi 1001
          (entry.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)?'A':' ',
1002
          (entry.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)?'S':' ',
1003
          (entry.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)?'H':' ',
2031 mateusz.vi 1004
          (entry.dwFileAttributes & FILE_ATTRIBUTE_READONLY)?'R':' '
2019 mateusz.vi 1005
        );
1006
 
1007
      if (dspSize)  /* file size */
1008
      {
1009
        if (entry.nFileSizeHigh)
1010
        {
1011
          pprintf("******** ");  /* error exceed max value we can display, > 4GB */
1012
        }
1013
        else
1014
        {
2023 mateusz.vi 1015
          if (entry.nFileSizeLow < 1048576l)  /* if less than a MB, display in bytes */
2019 mateusz.vi 1016
            pprintf("%10lu ", entry.nFileSizeLow);
1017
          else                               /* otherwise display in KB */
1018
            pprintf("%8luKB ", entry.nFileSizeLow/1024UL);
1019
        }
1020
      }
1021
 
1022
      /* print filename */
1023
      pprintf("%s\n", entry.cFileName);
1024
 
1025
      filesShown++;
1026
    }
1027
  } while(FindNextFile(dir, &entry) != 0);
1028
 
1029
  if (filesShown)
1030
  {
1031
    pprintf("%s\n", padding);
1032
  }
1033
 
1034
  /* cleanup directory search */
1035
  FindClose(dir);
1036
  /* dir = NULL; */
1037
 
1038
  removePadding(padding);
1039
 
1040
  /* store for summary display */
1041
  if (ddata != NULL) ddata->fileCnt = filesShown;
1042
 
1043
  return (filesShown)? 1 : 0;
1044
}
1045
 
1046
 
1047
/**
1048
 * Common portion of findFirstSubdir and findNextSubdir
1049
 * Checks current FindFile results to determine if a valid directory
1050
 * was found, and if so copies appropriate data into subdir and dsubdir.
1051
 * It will repeat until a valid subdirectory is found or no more
1052
 * are found, at which point it closes the FindFile search handle and
1053
 * return INVALID_HANDLE_VALUE.  If successful, returns FindFile handle.
1054
 */
2038 mateusz.vi 1055
static HANDLE cycleFindResults(HANDLE findnexthnd, WIN32_FIND_DATAA *entry, char *subdir, char *dsubdir) {
2025 mateusz.vi 1056
  /* cycle through directory until 1st non . or .. directory is found. */
1057
  do
2019 mateusz.vi 1058
  {
2025 mateusz.vi 1059
    /* skip files & hidden or system directories */
2038 mateusz.vi 1060
    if ((((entry->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) ||
1061
         ((entry->dwFileAttributes &
2025 mateusz.vi 1062
          (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0  && !dspAll) ) ||
2038 mateusz.vi 1063
        ((strcmp(entry->cFileName, ".") == 0) ||
1064
         (strcmp(entry->cFileName, "..") == 0)) )
2019 mateusz.vi 1065
    {
2038 mateusz.vi 1066
      if (FindNextFile(findnexthnd, entry) == 0)
2019 mateusz.vi 1067
      {
2025 mateusz.vi 1068
        FindClose(findnexthnd);      // prevent resource leaks
1069
        return INVALID_HANDLE_VALUE; // no subdirs found
2019 mateusz.vi 1070
      }
2025 mateusz.vi 1071
    }
1072
    else
2019 mateusz.vi 1073
    {
2025 mateusz.vi 1074
      /* set display name */
2038 mateusz.vi 1075
      strcpy(dsubdir, entry->cFileName);
2019 mateusz.vi 1076
 
2025 mateusz.vi 1077
      /* set canical name to use for further FindFile calls */
1078
      /* use short file name if exists as lfn may contain unicode values converted
1079
       * to default character (eg. ?) and so not a valid path.
1080
       */
2038 mateusz.vi 1081
      strcpy(subdir, entry->cFileName);
2025 mateusz.vi 1082
      strcat(subdir, "\\");
1083
    }
1084
  } while (!*subdir); // while (subdir is still blank)
1085
 
2019 mateusz.vi 1086
  return findnexthnd;
1087
}
1088
 
1089
 
1090
/* FindFile buffer used by findFirstSubdir and findNextSubdir only */
2038 mateusz.vi 1091
static WIN32_FIND_DATAA findSubdir_entry; /* current directory entry info    */
2019 mateusz.vi 1092
 
1093
/**
1094
 * Given the current path, find the 1st subdirectory.
1095
 * The subdirectory found is stored in subdir.
1096
 * subdir is cleared on error or no subdirectories.
1097
 * Returns the findfirst search HANDLE, which should be passed to
1098
 * findclose when directory has finished processing, and can be
1099
 * passed to findnextsubdir to find subsequent subdirectories.
1100
 * Returns INVALID_HANDLE_VALUE on error.
1101
 * currentpath must end in \
1102
 */
2037 mateusz.vi 1103
static HANDLE findFirstSubdir(char *currentpath, char *subdir, char *dsubdir) {
2019 mateusz.vi 1104
  static char buffer[MAXBUF];
1105
  HANDLE dir;         /* Current directory entry working with      */
1106
 
1107
  /* get handle for files in current directory (using wildcard spec) */
1108
  strcpy(buffer, currentpath);
1109
  strcat(buffer, "*");
1110
 
2038 mateusz.vi 1111
  dir = FindFirstFileA(buffer, &findSubdir_entry);
2019 mateusz.vi 1112
  if (dir == INVALID_HANDLE_VALUE)
1113
  {
1114
    showInvalidPath(currentpath);
1115
    return INVALID_HANDLE_VALUE;
1116
  }
1117
 
1118
  /* clear result path */
1119
  strcpy(subdir, "");
1120
 
2032 mateusz.vi 1121
  return cycleFindResults(dir, &findSubdir_entry, subdir, dsubdir);
2019 mateusz.vi 1122
}
1123
 
1124
/**
2022 mateusz.vi 1125
 * Given a search HANDLE, will find the next subdirectory,
2019 mateusz.vi 1126
 * setting subdir to the found directory name.
1127
 * dsubdir is the name to display (lfn or sfn as appropriate)
1128
 * currentpath must end in \
1129
 * If a subdirectory is found, returns 0, otherwise returns 1
1130
 * (either error or no more files).
1131
 */
2037 mateusz.vi 1132
static int findNextSubdir(HANDLE findnexthnd, char *subdir, char *dsubdir) {
2019 mateusz.vi 1133
  /* clear result path */
1134
  strcpy(subdir, "");
1135
 
2038 mateusz.vi 1136
  if (FindNextFile(findnexthnd, &findSubdir_entry) == 0) return 1; // no subdirs found
2019 mateusz.vi 1137
 
2032 mateusz.vi 1138
  if (cycleFindResults(findnexthnd, &findSubdir_entry, subdir, dsubdir) == INVALID_HANDLE_VALUE)
2019 mateusz.vi 1139
    return 1;
1140
  else
1141
    return 0;
1142
}
1143
 
1144
/**
1145
 * Given an initial path, displays the directory tree with
1146
 * a non-recursive function using a Stack.
1147
 * initialpath must be large enough to hold an added slash \ or /
1148
 * if it does not already end in one.
1149
 * Returns the count of subdirs in initialpath.
1150
 */
2037 mateusz.vi 1151
static long traverseTree(char *initialpath) {
2019 mateusz.vi 1152
  long subdirsInInitialpath;
1153
  char padding[MAXPADLEN] = "";
1154
  char subdir[MAXBUF];
1155
  char dsubdir[MAXBUF];
2027 mateusz.vi 1156
  SUBDIRINFO *sdi;
2019 mateusz.vi 1157
 
1158
  STACK s;
1159
  stackDefaults(&s);
1160
  stackInit(&s);
1161
 
1162
  if ( (sdi = newSubdirInfo(NULL, initialpath, initialpath)) == NULL)
1163
    return 0L;
1164
  stackPushItem(&s, sdi);
1165
 
1166
  /* Store count of subdirs in initial path so can display message if none. */
1167
  subdirsInInitialpath = sdi->subdircnt;
1168
 
1169
  do
1170
  {
1171
    sdi = (SUBDIRINFO *)stackPopItem(&s);
1172
 
1173
    if (sdi->findnexthnd == INVALID_HANDLE_VALUE)  // findfirst not called yet
1174
    {
1175
      // 1st time this subdirectory processed, so display its name & possibly files
1176
      if (sdi->parent == NULL) // if initial path
1177
      {
1178
        // display initial path
1179
        showCurrentPath(/*sdi->dsubdir*/initialpath, NULL, -1, &(sdi->ddata));
1180
      }
1181
      else // normal processing (display path, add necessary padding)
1182
      {
1183
        showCurrentPath(sdi->dsubdir, padding, (sdi->parent->subdircnt > 0L)?1 : 0, &(sdi->ddata));
1184
        addPadding(padding, (sdi->parent->subdircnt > 0L)?1 : 0);
1185
      }
1186
 
1187
      if (showFiles == SHOWFILESON)  displayFiles(sdi->currentpath, padding, (sdi->subdircnt > 0L)?1 : 0, &(sdi->ddata));
2024 mateusz.vi 1188
      displaySummary(padding, (sdi->subdircnt > 0L)?1 : 0, &(sdi->ddata));
2019 mateusz.vi 1189
    }
1190
 
1191
    if (sdi->subdircnt > 0) /* if (there are more subdirectories to process) */
1192
    {
1193
      int flgErr;
1194
      if (sdi->findnexthnd == INVALID_HANDLE_VALUE)
1195
      {
1196
        sdi->findnexthnd = findFirstSubdir(sdi->currentpath, subdir, dsubdir);
1197
        flgErr = (sdi->findnexthnd == INVALID_HANDLE_VALUE);
1198
      }
1199
      else
1200
      {
1201
        flgErr = findNextSubdir(sdi->findnexthnd, subdir, dsubdir);
1202
      }
1203
 
1204
      if (flgErr) // don't add invalid paths to stack
1205
      {
1206
        printf("INTERNAL ERROR: subdir count changed, expecting %li more!\n", sdi->subdircnt+1L);
1207
 
1208
        sdi->subdircnt = 0; /* force subdir counter to 0, none left */
1209
        stackPushItem(&s, sdi);
1210
      }
1211
      else
1212
      {
1213
        sdi->subdircnt = sdi->subdircnt - 1L; /* decrement subdirs left count */
1214
        stackPushItem(&s, sdi);
1215
 
1216
        /* store necessary information, validate subdir, and if no error store it. */
1217
        if ((sdi = newSubdirInfo(sdi, subdir, dsubdir)) != NULL)
1218
          stackPushItem(&s, sdi);
1219
      }
1220
    }
1221
    else /* this directory finished processing, so free resources */
1222
    {
1223
      /* Remove the padding for this directory, all but initial path. */
1224
      if (sdi->parent != NULL)
1225
        removePadding(padding);
1226
 
1227
      /* Prevent resource leaks, by ending findsearch and freeing memory. */
1228
      FindClose(sdi->findnexthnd);
1229
      if (sdi != NULL)
1230
      {
1231
        if (sdi->currentpath != NULL)
1232
          free(sdi->currentpath);
1233
        free(sdi);
1234
      }
1235
    }
1236
  } while (stackTotalItems(&s)); /* while (stack is not empty) */
1237
 
1238
  stackTerm(&s);
1239
 
1240
  return subdirsInInitialpath;
1241
}
1242
 
1243
 
1244
/**
1245
 * Process strings, converting \\, \n, \r, and \t to actual chars.
1246
 * This method is used to allow the message catalog to use \\, \n, \r, and \t
1247
 * returns a pointer to its internal buffer, so strcpy soon after use.
1248
 * Can only handle lines up to MAXLINE chars.
1249
 * This is required because most messages are passed as
1250
 * string arguments to printf, and not actually parsed by it.
1251
 */
2037 mateusz.vi 1252
static char *processLine(char *line) {
2019 mateusz.vi 1253
  static char buffer[MAXLINE+MAXLINE];
2027 mateusz.vi 1254
  char *src = line, *dst = buffer;
2019 mateusz.vi 1255
 
1256
  if (line == NULL) return NULL;
1257
 
1258
  /* cycle through copying characters, except when a \ is encountered. */
1259
  for ( ; *src != '\0'; src++, dst++)
1260
  {
1261
    if (*src == '\\')
1262
    {
1263
      src++;
1264
      switch (*src)
1265
      {
1266
	  case '\0': /* a slash ends a line, ignore the slash. */
1267
		  src--; /* next time through will see the '\0'    */
1268
		  break;
1269
	  case '\\': /* a single slash */
1270
		  *dst = '\\';
1271
		  break;
1272
	  case 'n': /* a newline */
1273
		  *dst = '\n';
1274
		  break;
1275
	  case 'r': /* a carriage return */
1276
		  *dst = '\r';
1277
		  break;
1278
	  case 't': /* a horizontal tab */
1279
		  *dst = '\t';
1280
		  break;
1281
	  default: /* just copy over the letter */
1282
		  *dst = *src;
1283
		  break;
1284
      }
1285
    }
1286
    else
1287
      *dst = *src;
1288
  }
1289
 
1290
  /* ensure '\0' terminated */
1291
  *dst = '\0';
1292
 
1293
  return buffer;
1294
}
1295
 
1296
 
2037 mateusz.vi 1297
static void FixOptionText(void) {
2019 mateusz.vi 1298
  char buffer[MAXLINE];  /* sprintf can have problems with src==dest */
1299
 
1300
  /* Handle %c for options within messages using Set 8 */
1301
  strcpy(buffer, treeUsage);
1302
  sprintf(treeUsage, buffer, optionchar1, OptShowFiles[0], optionchar1, OptUseASCII[0]);
1303
  strcpy(buffer, treeFOption);
1304
  sprintf(treeFOption, buffer, optionchar1, OptShowFiles[0]);
1305
  strcpy(buffer, treeAOption);
1306
  sprintf(treeAOption, buffer, optionchar1, OptUseASCII[0]);
1307
  strcpy(buffer, useTreeHelp);
1308
  sprintf(useTreeHelp, buffer, optionchar1);
1309
}
1310
 
1311
 
2022 mateusz.vi 1312
/* Loads all messages from the message catalog. */
2037 mateusz.vi 1313
static void loadAllMessages(void) {
2019 mateusz.vi 1314
  /* Changes %c in certain lines with proper option characters. */
1315
  FixOptionText();
1316
}
1317
 
1318
 
2037 mateusz.vi 1319
int main(int argc, char **argv) {
2019 mateusz.vi 1320
  char serial[SERIALLEN]; /* volume serial #  0000:0000 */
1321
  char volume[VOLLEN];    /* volume name (label), possibly none */
1322
 
1323
  /* Load all text from message catalog (or uses hard coded text) */
1324
  loadAllMessages();
1325
 
1326
  /* Parse any command line arguments, obtain path */
1327
  parseArguments(argc, argv);
1328
 
1329
  /* Initialize screen size, may reset pause to NOPAUSE if redirected */
1330
  getConsoleSize();
1331
 
1332
  /* Get Volume & Serial Number */
1333
  GetVolumeAndSerial(volume, serial, path);
1334
  if (strlen(volume) == 0)
1335
    pprintf(pathListingNoLabel);
1336
  else
1337
    pprintf(pathListingWithLabel, volume);
1338
  if (serial[0] != '\0')  /* Don't print anything if no serial# found */
1339
    pprintf(serialNumber, serial);
1340
 
1341
  /* now traverse & print tree, returns nonzero if has subdirectories */
1342
  if (traverseTree(path) == 0)
1343
    pprintf(noSubDirs);
1344
  else if (dspSumDirs) /* show count of directories processed */
1345
    pprintf("\n    %lu total directories\n", totalSubDirCnt+1);
1346
 
1347
  return 0;
1348
}