Subversion Repositories SvarDOS

Rev

Rev 2045 | 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  */
2046 mateusz.vi 621
  struct FFDTA *findnexthnd; /* The handle returned by findfirst, used in findnext */
2019 mateusz.vi 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;
2046 mateusz.vi 635
  struct FFDTA *hnd;
2019 mateusz.vi 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);
2046 mateusz.vi 648
  if (hnd == INVALID_HANDLE_VALUE) {
2019 mateusz.vi 649
    showInvalidPath(path); /* Display error message */
650
    return -1L;
651
  }
652
 
653
 
654
  /*  cycle through entries counting directories found until no more entries */
655
  do {
656
    if (((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) &&
657
	((findData.dwFileAttributes &
658
	 (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) == 0 || dspAll) )
659
    {
660
      if ( (strcmp(findData.cFileName, ".") != 0) && /* ignore initial [current] path */
661
           (strcmp(findData.cFileName, "..") != 0) ) /* and ignore parent path */
662
        hasSubdirs++;      /* subdir of initial path found, so increment counter */
663
    }
664
  } while(FindNextFile(hnd, &findData) != 0);
665
 
666
  /* prevent resource leaks, close the handle. */
667
  FindClose(hnd);
668
 
669
  if (ddata != NULL)  // don't bother if user doesn't want them
670
  {
671
    /* The root directory of a volume (including non root paths
672
       corresponding to mount points) may not have a current (.) and
673
       parent (..) entry.  So we can't get attributes for initial
2022 mateusz.vi 674
       path in above loop from the FindFile call as it may not show up
2019 mateusz.vi 675
       (no . entry).  So instead we explicitly get them here.
676
    */
677
    if ((ddata->dwDirAttributes = GetFileAttributes(path)) == (DWORD)-1)
678
    {
679
      //printf("ERROR: unable to get file attr, %i\n", GetLastError());
680
      ddata->dwDirAttributes = 0;
681
    }
682
 
683
    /* a curiosity, for showing sum of directories process */
684
    ddata->subdirCnt = hasSubdirs;
685
  }
686
  totalSubDirCnt += hasSubdirs;
687
 
688
  return hasSubdirs;
689
}
690
 
691
 
692
/**
693
 * Allocates memory and stores the necessary stuff to allow us to
694
 * come back to this subdirectory after handling its subdirectories.
695
 * parentpath must end in \ or / or be NULL, however
696
 * parent should only be NULL for initialpath
697
 * if subdir does not end in slash, one is added to stored subdir
698
 * dsubdir is subdir already modified so ready to display to user
699
 */
2037 mateusz.vi 700
static SUBDIRINFO *newSubdirInfo(SUBDIRINFO *parent, char *subdir, char *dsubdir) {
2027 mateusz.vi 701
  int parentLen, subdirLen;
2032 mateusz.vi 702
  SUBDIRINFO *temp;
2019 mateusz.vi 703
 
704
  /* Get length of parent directory */
705
  if (parent == NULL)
706
    parentLen = 0;
707
  else
708
    parentLen = strlen(parent->currentpath);
709
 
710
  /* Get length of subdir, add 1 if does not end in slash */
711
  subdirLen = strlen(subdir);
712
  if ((subdirLen < 1) || ( (*(subdir+subdirLen-1) != '\\') && (*(subdir+subdirLen-1) != '/') ) )
713
    subdirLen++;
714
 
2032 mateusz.vi 715
  temp = (SUBDIRINFO *)malloc(sizeof(SUBDIRINFO));
2022 mateusz.vi 716
  if (temp == NULL)
2019 mateusz.vi 717
  {
718
    showOutOfMemory(subdir);
719
    return NULL;
720
  }
721
  if ( ((temp->currentpath = (char *)malloc(parentLen+subdirLen+1)) == NULL) ||
722
       ((temp->dsubdir = (char *)malloc(strlen(dsubdir)+1)) == NULL) )
723
  {
724
    showOutOfMemory(subdir);
725
    if (temp->currentpath != NULL) free(temp->currentpath);
726
    free(temp);
727
    return NULL;
728
  }
729
  temp->parent = parent;
730
  if (parent == NULL)
731
    strcpy(temp->currentpath, "");
732
  else
733
    strcpy(temp->currentpath, parent->currentpath);
734
  strcat(temp->currentpath, subdir);
735
  /* if subdir[subdirLen-1] == '\0' then we must append a slash */
736
  if (*(subdir+subdirLen-1) == '\0')
737
    strcat(temp->currentpath, "\\");
738
  temp->subdir = temp->currentpath+parentLen;
739
  strcpy(temp->dsubdir, dsubdir);
740
  if ((temp->subdircnt = hasSubdirectories(temp->currentpath, &(temp->ddata))) == -1L)
741
  {
742
    free (temp->currentpath);
743
    free (temp->dsubdir);
744
    free(temp);
745
    return NULL;
746
  }
747
  temp->findnexthnd = INVALID_HANDLE_VALUE;
748
 
749
  return temp;
750
}
751
 
752
/**
753
 * Extends the padding with the necessary 4 characters.
754
 * Returns the pointer to the padding.
2022 mateusz.vi 755
 * padding should be large enough to hold the additional
2019 mateusz.vi 756
 * characters and '\0', moreSubdirsFollow specifies if
757
 * this is the last subdirectory in a given directory
758
 * or if more follow (hence if a | is needed).
759
 * padding must not be NULL
760
 */
2037 mateusz.vi 761
static char * addPadding(char *padding, int moreSubdirsFollow) {
762
  if (moreSubdirsFollow) {
763
    /* 1st char is | or a vertical bar */
764
    if (charSet == EXTENDEDCHARS) {
765
      strcat(padding, VERTBAR_STR);
766
    } else {
767
      strcat(padding, "|   ");
2019 mateusz.vi 768
    }
2037 mateusz.vi 769
  } else {
770
    strcat(padding, "    ");
771
  }
2019 mateusz.vi 772
 
2037 mateusz.vi 773
  return(padding);
2019 mateusz.vi 774
}
775
 
776
/**
2025 mateusz.vi 777
 * Removes the last padding added (last 4 characters added).
778
 * Does nothing if less than 4 characters in string.
2019 mateusz.vi 779
 * padding must not be NULL
780
 * Returns the pointer to padding.
781
 */
2037 mateusz.vi 782
static char *removePadding(char *padding) {
2027 mateusz.vi 783
  size_t len = strlen(padding);
2019 mateusz.vi 784
 
2025 mateusz.vi 785
  if (len < 4) return padding;
786
  *(padding + len - 4) = '\0';
2019 mateusz.vi 787
 
788
  return padding;
789
}
790
 
791
/**
792
 * Takes a given path, strips any \ or / that may appear on the end.
793
 * Returns a pointer to its static buffer containing path
794
 * without trailing slash and any necessary display conversions.
795
 */
2037 mateusz.vi 796
static char *fixPathForDisplay(char *path) {
2019 mateusz.vi 797
  static char buffer[MAXBUF];
2027 mateusz.vi 798
  int pathlen;
2019 mateusz.vi 799
 
800
  strcpy(buffer, path);
801
  pathlen = strlen(buffer);
2037 mateusz.vi 802
  if (pathlen > 1) {
2019 mateusz.vi 803
    pathlen--;
2037 mateusz.vi 804
    if ((buffer[pathlen] == '\\') || (buffer[pathlen] == '/')) {
2019 mateusz.vi 805
      buffer[pathlen] = '\0'; // strip off trailing slash on end
2037 mateusz.vi 806
    }
2019 mateusz.vi 807
  }
808
 
809
  return buffer;
810
}
811
 
812
/**
813
 * Displays the current path, with necessary padding before it.
814
 * A \ or / on end of currentpath is not shown.
815
 * moreSubdirsFollow should be nonzero if this is not the last
816
 * subdirectory to be displayed in current directory, else 0.
817
 * Also displays additional information, such as attributes or
818
 * sum of size of included files.
819
 * currentpath is an ASCIIZ string of path to display
820
 *             assumed to be a displayable path (ie. OEM or UTF-8)
821
 * padding is an ASCIIZ string to display prior to entry.
822
 * moreSubdirsFollow is -1 for initial path else >= 0.
823
 */
2037 mateusz.vi 824
static void showCurrentPath(char *currentpath, char *padding, int moreSubdirsFollow, DIRDATA *ddata) {
2019 mateusz.vi 825
  if (padding != NULL)
826
    pprintf("%s", padding);
827
 
828
  /* print lead padding except for initial directory */
829
  if (moreSubdirsFollow >= 0)
830
  {
831
    if (charSet == EXTENDEDCHARS)
832
    {
833
      if (moreSubdirsFollow)
834
        pprintf("%s", TBAR_HORZBAR_STR);
835
      else
836
        pprintf("%s", CBAR_HORZBAR_STR);
2037 mateusz.vi 837
    } else {
2019 mateusz.vi 838
      if (moreSubdirsFollow)
839
        pprintf("+---");
840
      else
841
        pprintf("\\---");
842
    }
843
  }
844
 
845
  /* optional display data */
846
  if (dspAttr)  /* attributes */
2031 mateusz.vi 847
    pprintf("[%c%c%c%c%c] ",
2019 mateusz.vi 848
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_DIRECTORY)?'D':' ',  /* keep this one? its always true */
849
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_ARCHIVE)?'A':' ',
850
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_SYSTEM)?'S':' ',
851
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_HIDDEN)?'H':' ',
2031 mateusz.vi 852
      (ddata->dwDirAttributes & FILE_ATTRIBUTE_READONLY)?'R':' '
2019 mateusz.vi 853
    );
854
 
855
  /* display directory name */
856
  pprintf("%s\n", currentpath);
857
}
858
 
859
 
2022 mateusz.vi 860
/**
2019 mateusz.vi 861
 * Displays summary information about directory.
862
 * Expects to be called after displayFiles (optionally called)
863
 */
2037 mateusz.vi 864
static void displaySummary(char *padding, int hasMoreSubdirs, DIRDATA *ddata) {
2019 mateusz.vi 865
  addPadding(padding, hasMoreSubdirs);
866
 
2037 mateusz.vi 867
  if (dspSumDirs) {
868
    if (showFiles == SHOWFILESON) {
2019 mateusz.vi 869
      /* print File summary with lead padding, add filesize to it */
870
      pprintf("%s%lu files\n", padding, ddata->fileCnt);
871
    }
872
 
873
    /* print Directory summary with lead padding */
874
    pprintf("%s%lu subdirectories\n", padding, ddata->subdirCnt);
875
 
876
    /* show [nearly] blank line after summary */
877
    pprintf("%s\n", padding);
878
  }
879
 
880
  removePadding(padding);
881
}
882
 
2022 mateusz.vi 883
/**
2019 mateusz.vi 884
 * Displays files in directory specified by path.
885
 * Path must end in slash \ or /
886
 * Returns -1 on error,
887
 *          0 if no files, but no errors either,
888
 *      or  1 if files displayed, no errors.
889
 */
2037 mateusz.vi 890
static int displayFiles(char *path, char *padding, int hasMoreSubdirs, DIRDATA *ddata) {
2019 mateusz.vi 891
  static char buffer[MAXBUF];
2040 mateusz.vi 892
  struct WIN32_FIND_DATA entry; /* current directory entry info    */
2046 mateusz.vi 893
  struct FFDTA *dir;         /* Current directory entry working with      */
2019 mateusz.vi 894
  unsigned long filesShown = 0;
895
 
896
  /* get handle for files in current directory (using wildcard spec) */
897
  strcpy(buffer, path);
898
  strcat(buffer, "*");
899
  dir = FindFirstFile(buffer, &entry);
900
  if (dir == INVALID_HANDLE_VALUE)
901
    return -1;
902
 
903
  addPadding(padding, hasMoreSubdirs);
904
 
905
  /* cycle through directory printing out files. */
2022 mateusz.vi 906
  do
2019 mateusz.vi 907
  {
908
    /* print padding followed by filename */
909
    if ( ((entry.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) &&
910
         ( ((entry.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN |
911
         FILE_ATTRIBUTE_SYSTEM)) == 0)  || dspAll) )
912
    {
913
      /* print lead padding */
914
      pprintf("%s", padding);
915
 
916
      /* optional display data */
917
      if (dspAttr)  /* file attributes */
2031 mateusz.vi 918
        pprintf("[%c%c%c%c] ",
2019 mateusz.vi 919
          (entry.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE)?'A':' ',
920
          (entry.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM)?'S':' ',
921
          (entry.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN)?'H':' ',
2031 mateusz.vi 922
          (entry.dwFileAttributes & FILE_ATTRIBUTE_READONLY)?'R':' '
2019 mateusz.vi 923
        );
924
 
925
      if (dspSize)  /* file size */
926
      {
927
        if (entry.nFileSizeHigh)
928
        {
929
          pprintf("******** ");  /* error exceed max value we can display, > 4GB */
930
        }
931
        else
932
        {
2023 mateusz.vi 933
          if (entry.nFileSizeLow < 1048576l)  /* if less than a MB, display in bytes */
2019 mateusz.vi 934
            pprintf("%10lu ", entry.nFileSizeLow);
935
          else                               /* otherwise display in KB */
936
            pprintf("%8luKB ", entry.nFileSizeLow/1024UL);
937
        }
938
      }
939
 
940
      /* print filename */
941
      pprintf("%s\n", entry.cFileName);
942
 
943
      filesShown++;
944
    }
945
  } while(FindNextFile(dir, &entry) != 0);
946
 
947
  if (filesShown)
948
  {
949
    pprintf("%s\n", padding);
950
  }
951
 
952
  /* cleanup directory search */
953
  FindClose(dir);
954
  /* dir = NULL; */
955
 
956
  removePadding(padding);
957
 
958
  /* store for summary display */
959
  if (ddata != NULL) ddata->fileCnt = filesShown;
960
 
961
  return (filesShown)? 1 : 0;
962
}
963
 
964
 
965
/**
966
 * Common portion of findFirstSubdir and findNextSubdir
967
 * Checks current FindFile results to determine if a valid directory
968
 * was found, and if so copies appropriate data into subdir and dsubdir.
969
 * It will repeat until a valid subdirectory is found or no more
970
 * are found, at which point it closes the FindFile search handle and
971
 * return INVALID_HANDLE_VALUE.  If successful, returns FindFile handle.
972
 */
2046 mateusz.vi 973
static struct FFDTA *cycleFindResults(struct FFDTA *findnexthnd, struct WIN32_FIND_DATA *entry, char *subdir, char *dsubdir) {
2025 mateusz.vi 974
  /* cycle through directory until 1st non . or .. directory is found. */
975
  do
2019 mateusz.vi 976
  {
2025 mateusz.vi 977
    /* skip files & hidden or system directories */
2038 mateusz.vi 978
    if ((((entry->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) ||
979
         ((entry->dwFileAttributes &
2025 mateusz.vi 980
          (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0  && !dspAll) ) ||
2038 mateusz.vi 981
        ((strcmp(entry->cFileName, ".") == 0) ||
982
         (strcmp(entry->cFileName, "..") == 0)) )
2019 mateusz.vi 983
    {
2038 mateusz.vi 984
      if (FindNextFile(findnexthnd, entry) == 0)
2019 mateusz.vi 985
      {
2025 mateusz.vi 986
        FindClose(findnexthnd);      // prevent resource leaks
987
        return INVALID_HANDLE_VALUE; // no subdirs found
2019 mateusz.vi 988
      }
2025 mateusz.vi 989
    }
990
    else
2019 mateusz.vi 991
    {
2025 mateusz.vi 992
      /* set display name */
2038 mateusz.vi 993
      strcpy(dsubdir, entry->cFileName);
2019 mateusz.vi 994
 
2038 mateusz.vi 995
      strcpy(subdir, entry->cFileName);
2025 mateusz.vi 996
      strcat(subdir, "\\");
997
    }
998
  } while (!*subdir); // while (subdir is still blank)
999
 
2019 mateusz.vi 1000
  return findnexthnd;
1001
}
1002
 
1003
 
1004
/* FindFile buffer used by findFirstSubdir and findNextSubdir only */
2040 mateusz.vi 1005
static struct WIN32_FIND_DATA findSubdir_entry; /* current directory entry info    */
2019 mateusz.vi 1006
 
1007
/**
1008
 * Given the current path, find the 1st subdirectory.
1009
 * The subdirectory found is stored in subdir.
1010
 * subdir is cleared on error or no subdirectories.
1011
 * Returns the findfirst search HANDLE, which should be passed to
1012
 * findclose when directory has finished processing, and can be
1013
 * passed to findnextsubdir to find subsequent subdirectories.
1014
 * Returns INVALID_HANDLE_VALUE on error.
1015
 * currentpath must end in \
1016
 */
2046 mateusz.vi 1017
static struct FFDTA *findFirstSubdir(char *currentpath, char *subdir, char *dsubdir) {
2019 mateusz.vi 1018
  static char buffer[MAXBUF];
2046 mateusz.vi 1019
  struct FFDTA *dir;         /* Current directory entry working with      */
2019 mateusz.vi 1020
 
1021
  /* get handle for files in current directory (using wildcard spec) */
1022
  strcpy(buffer, currentpath);
1023
  strcat(buffer, "*");
1024
 
2040 mateusz.vi 1025
  dir = FindFirstFile(buffer, &findSubdir_entry);
2046 mateusz.vi 1026
  if (dir == INVALID_HANDLE_VALUE) {
2019 mateusz.vi 1027
    showInvalidPath(currentpath);
1028
    return INVALID_HANDLE_VALUE;
1029
  }
1030
 
1031
  /* clear result path */
1032
  strcpy(subdir, "");
1033
 
2032 mateusz.vi 1034
  return cycleFindResults(dir, &findSubdir_entry, subdir, dsubdir);
2019 mateusz.vi 1035
}
1036
 
1037
/**
2022 mateusz.vi 1038
 * Given a search HANDLE, will find the next subdirectory,
2019 mateusz.vi 1039
 * setting subdir to the found directory name.
2045 mateusz.vi 1040
 * dsubdir is the name to display
2019 mateusz.vi 1041
 * currentpath must end in \
1042
 * If a subdirectory is found, returns 0, otherwise returns 1
1043
 * (either error or no more files).
1044
 */
2046 mateusz.vi 1045
static int findNextSubdir(struct FFDTA *findnexthnd, char *subdir, char *dsubdir) {
2019 mateusz.vi 1046
  /* clear result path */
1047
  strcpy(subdir, "");
1048
 
2038 mateusz.vi 1049
  if (FindNextFile(findnexthnd, &findSubdir_entry) == 0) return 1; // no subdirs found
2019 mateusz.vi 1050
 
2032 mateusz.vi 1051
  if (cycleFindResults(findnexthnd, &findSubdir_entry, subdir, dsubdir) == INVALID_HANDLE_VALUE)
2019 mateusz.vi 1052
    return 1;
1053
  else
1054
    return 0;
1055
}
1056
 
1057
/**
1058
 * Given an initial path, displays the directory tree with
1059
 * a non-recursive function using a Stack.
1060
 * initialpath must be large enough to hold an added slash \ or /
1061
 * if it does not already end in one.
1062
 * Returns the count of subdirs in initialpath.
1063
 */
2037 mateusz.vi 1064
static long traverseTree(char *initialpath) {
2019 mateusz.vi 1065
  long subdirsInInitialpath;
1066
  char padding[MAXPADLEN] = "";
1067
  char subdir[MAXBUF];
1068
  char dsubdir[MAXBUF];
2027 mateusz.vi 1069
  SUBDIRINFO *sdi;
2019 mateusz.vi 1070
 
1071
  STACK s;
1072
  stackDefaults(&s);
1073
  stackInit(&s);
1074
 
1075
  if ( (sdi = newSubdirInfo(NULL, initialpath, initialpath)) == NULL)
1076
    return 0L;
1077
  stackPushItem(&s, sdi);
1078
 
1079
  /* Store count of subdirs in initial path so can display message if none. */
1080
  subdirsInInitialpath = sdi->subdircnt;
1081
 
1082
  do
1083
  {
1084
    sdi = (SUBDIRINFO *)stackPopItem(&s);
1085
 
1086
    if (sdi->findnexthnd == INVALID_HANDLE_VALUE)  // findfirst not called yet
1087
    {
1088
      // 1st time this subdirectory processed, so display its name & possibly files
1089
      if (sdi->parent == NULL) // if initial path
1090
      {
1091
        // display initial path
1092
        showCurrentPath(/*sdi->dsubdir*/initialpath, NULL, -1, &(sdi->ddata));
1093
      }
1094
      else // normal processing (display path, add necessary padding)
1095
      {
1096
        showCurrentPath(sdi->dsubdir, padding, (sdi->parent->subdircnt > 0L)?1 : 0, &(sdi->ddata));
1097
        addPadding(padding, (sdi->parent->subdircnt > 0L)?1 : 0);
1098
      }
1099
 
1100
      if (showFiles == SHOWFILESON)  displayFiles(sdi->currentpath, padding, (sdi->subdircnt > 0L)?1 : 0, &(sdi->ddata));
2024 mateusz.vi 1101
      displaySummary(padding, (sdi->subdircnt > 0L)?1 : 0, &(sdi->ddata));
2019 mateusz.vi 1102
    }
1103
 
1104
    if (sdi->subdircnt > 0) /* if (there are more subdirectories to process) */
1105
    {
1106
      int flgErr;
1107
      if (sdi->findnexthnd == INVALID_HANDLE_VALUE)
1108
      {
1109
        sdi->findnexthnd = findFirstSubdir(sdi->currentpath, subdir, dsubdir);
1110
        flgErr = (sdi->findnexthnd == INVALID_HANDLE_VALUE);
1111
      }
1112
      else
1113
      {
1114
        flgErr = findNextSubdir(sdi->findnexthnd, subdir, dsubdir);
1115
      }
1116
 
1117
      if (flgErr) // don't add invalid paths to stack
1118
      {
1119
        printf("INTERNAL ERROR: subdir count changed, expecting %li more!\n", sdi->subdircnt+1L);
1120
 
1121
        sdi->subdircnt = 0; /* force subdir counter to 0, none left */
1122
        stackPushItem(&s, sdi);
1123
      }
1124
      else
1125
      {
1126
        sdi->subdircnt = sdi->subdircnt - 1L; /* decrement subdirs left count */
1127
        stackPushItem(&s, sdi);
1128
 
1129
        /* store necessary information, validate subdir, and if no error store it. */
1130
        if ((sdi = newSubdirInfo(sdi, subdir, dsubdir)) != NULL)
1131
          stackPushItem(&s, sdi);
1132
      }
1133
    }
1134
    else /* this directory finished processing, so free resources */
1135
    {
1136
      /* Remove the padding for this directory, all but initial path. */
1137
      if (sdi->parent != NULL)
1138
        removePadding(padding);
1139
 
1140
      /* Prevent resource leaks, by ending findsearch and freeing memory. */
1141
      FindClose(sdi->findnexthnd);
1142
      if (sdi != NULL)
1143
      {
1144
        if (sdi->currentpath != NULL)
1145
          free(sdi->currentpath);
1146
        free(sdi);
1147
      }
1148
    }
1149
  } while (stackTotalItems(&s)); /* while (stack is not empty) */
1150
 
1151
  stackTerm(&s);
1152
 
1153
  return subdirsInInitialpath;
1154
}
1155
 
1156
 
2037 mateusz.vi 1157
static void FixOptionText(void) {
2019 mateusz.vi 1158
  char buffer[MAXLINE];  /* sprintf can have problems with src==dest */
1159
 
1160
  /* Handle %c for options within messages using Set 8 */
1161
  strcpy(buffer, treeUsage);
1162
  sprintf(treeUsage, buffer, optionchar1, OptShowFiles[0], optionchar1, OptUseASCII[0]);
1163
  strcpy(buffer, treeFOption);
1164
  sprintf(treeFOption, buffer, optionchar1, OptShowFiles[0]);
1165
  strcpy(buffer, treeAOption);
1166
  sprintf(treeAOption, buffer, optionchar1, OptUseASCII[0]);
1167
  strcpy(buffer, useTreeHelp);
1168
  sprintf(useTreeHelp, buffer, optionchar1);
1169
}
1170
 
1171
 
2022 mateusz.vi 1172
/* Loads all messages from the message catalog. */
2037 mateusz.vi 1173
static void loadAllMessages(void) {
2019 mateusz.vi 1174
  /* Changes %c in certain lines with proper option characters. */
1175
  FixOptionText();
1176
}
1177
 
1178
 
2037 mateusz.vi 1179
int main(int argc, char **argv) {
2019 mateusz.vi 1180
  char serial[SERIALLEN]; /* volume serial #  0000:0000 */
1181
  char volume[VOLLEN];    /* volume name (label), possibly none */
1182
 
1183
  /* Load all text from message catalog (or uses hard coded text) */
1184
  loadAllMessages();
1185
 
1186
  /* Parse any command line arguments, obtain path */
1187
  parseArguments(argc, argv);
1188
 
1189
  /* Initialize screen size, may reset pause to NOPAUSE if redirected */
1190
  getConsoleSize();
1191
 
1192
  /* Get Volume & Serial Number */
1193
  GetVolumeAndSerial(volume, serial, path);
1194
  if (strlen(volume) == 0)
1195
    pprintf(pathListingNoLabel);
1196
  else
1197
    pprintf(pathListingWithLabel, volume);
1198
  if (serial[0] != '\0')  /* Don't print anything if no serial# found */
1199
    pprintf(serialNumber, serial);
1200
 
1201
  /* now traverse & print tree, returns nonzero if has subdirectories */
1202
  if (traverseTree(path) == 0)
1203
    pprintf(noSubDirs);
1204
  else if (dspSumDirs) /* show count of directories processed */
1205
    pprintf("\n    %lu total directories\n", totalSubDirCnt+1);
1206
 
1207
  return 0;
1208
}