Subversion Repositories SvarDOS

Rev

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