Repository navigation
Expand file tree
/
Copy pathNdir32.cpp
More file actions
555 lines (485 loc) · 18.9 KB
/
Copy pathNdir32.cpp
File metadata and controls
555 lines (485 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//*************************************************************************
// Copyright (c) 1998-2026 Derell Licht
// NDIR32.CPP - The Ultimate directory program (32-bit).
//*************************************************************************
// DAN: Please update CHANGELOG.md with each change.
//*************************************************************************
#include <windows.h>
#include <stdio.h>
#include <stdlib.h> // getenv(), exit()
#include <ctype.h>
#include <tchar.h>
#include <algorithm> // fix: error: 'sort' is not a member of 'std'
#include "common.h"
#include "ndir32.h"
#include "conio32.h"
#include "qualify.h"
#include "treelist.h"
#include "version.h" // defines VER_NUMBER; auto-generated by Makefile from CHANGELOG.md
//lint -esym(864, target) Expression involving variable possibly depends on order of evaluation
//lint -esym(843, Version, ShortVersion) could be declared as const
TCHAR *Version = _T(" NDIR.EXE, Version " VER_NUMBER " ") ;
TCHAR *ShortVersion = _T(" NDIR " VER_NUMBER " ") ;
TCHAR ininame[MAX_PATH_LEN] = _T("");
// per Jason Hood, this turns off MinGW's command-line expansion,
// so we can handle wildcards like we want to.
int _CRT_glob = 0 ;
//*****************************************************************
// CONFIGURATION VARIABLES (new style)
//*****************************************************************
ndir_data n ;
uchar dtree_colors[MAX_DIR_ENTRY] ;
unsigned tree_level_limit = 0 ;
//*****************************************************************
// END OF CONFIGURATION VARIABLES
//*****************************************************************
ULONGLONG diskbytes, diskfree, clbytes ;
// TCHAR* target[20] ;
std::vector<std::wstring> target {};
// TCHAR volume_name[MAX_PATH_LEN] ;
std::wstring volume_name {};
// name of drive+path without filenames
std::wstring base_path {};
unsigned start, finish ;
TCHAR tempstr[MAXLINE] ;
TCHAR tline, vline, dline ;
unsigned filecount = 0 ;
unsigned columns ; // number of display columns on screen
//*********************************************************
// NDIR information screen
//*********************************************************
static std::vector<std::wstring> idtxt {
L" ",
L"Copyright 1990, 1993-2025 by:",
L" ",
L" Derell Licht",
L" Email: derelict@comcast.net",
L" Website: https://derelllicht.42web.io/index.htm",
L" ",
L"This program, NDIR.EXE, and its associated files, ",
L"are distributed under Creative Commons CC0 1.0 Universal",
L"https://creativecommons.org/publicdomain/zero/1.0/",
} ;
//*********************************************************
// NDIR help screen
// unused flags: j l
//*********************************************************
static std::vector<std::wstring> helptxt {
L" ",
L"USAGE: NDIR <filespecs> -options or /options !<exclusions>",
L" ",
L" OPTIONS FUNCTIONS",
L" -a * List ALL files (hidden, system, read-only, etc.).",
L" -a1 List attributes in HEX format.",
L" -c * Clear screen before listing.",
L" -p * Pause on full screen.",
L" -m * Minimize size of header and footer.",
L" -w * Use special colors for system/hidden/readonly files.",
L" -d dir TREE: normal size display (work with -s, -n (default), -r).",
L" -d2 dir TREE: file/directory counts",
L" -d3 dir TREE: mixed size and file/directory counts",
L" -d4 dir TREE: show maximum filename lengths",
L" -y * In dirtree mode, exclude .git folder",
L" -e Sort by extension.",
L" -n \" by name.",
L" -s \" by file size, smallest first.",
L" -t \" by Date, oldest first.",
L" -z \" by DOS order (no sort).",
L" -S0 Show sizes in mixed bytes/KB",
L" -S1 Show sizes in Kilobytes",
L" -S2 Show sizes in Megabytes",
L" -r * Reverse normal sort order.",
L" -1 Display one column, with name/size/date/attr.",
L" -2 \" two \" , with name/size/date.",
L" -4 \" four \" , with name/size.",
L" -6 \" six \" , with name only.",
L" -i Display drive summary for all drives in system.",
L" -ii Display drive summary for all drives in system, with used vs free space.",
// L" -k * Toggle color mode.",
// L" -u * List filenames in UPPERCASE.",
L" -oN Date/Time display: 0=Last Write, 1=Last Access, 2=File Created",
L" -x * List executables only (.EXE,.COM,.BAT).",
L" -v Display registration/update information.",
L" -? Display HELP screen.",
L" -g * List directories FIRST.",
L" -h * List files horizontally.",
L" -f * List files only (No directories).",
L" -q * XTDIR mode - list files by extension.",
L" -, * Dir Tree: show only L level of subdirectories.",
L" L is incremented for each additional comma",
L" ",
L" -b Batch mode; files listed in one column.",
L" (This format can be redirected to a batch file)",
L" [\"string\" specifies a string BEFORE each filename (Batch mode)",
L" ]\"string\" specifies a string AFTER each filename (Batch mode)",
L" ",
L"NOTE: items with a * after the flag are TOGGLES",
L" ",
} ;
//**************************************************
static void info(std::vector<std::wstring>& data)
{
for(auto &file : data) {
dputsf(L"%s\n", file.c_str());
}
}
//**************************************************
// #define USE_SYSLOG
//lint -esym(714, dump_target)
//lint -esym(759, dump_target)
//lint -esym(765, dump_target)
void dump_target(TCHAR *msg)
{
if (msg != NULL) {
#ifdef USE_SYSLOG
syslog(_T("%s"), msg);
#else
dputsf(_T("%s\n"), msg);
#endif
}
for(auto &tgt : target) {
auto &telement = tgt ;
#ifdef USE_SYSLOG
syslog(L"%s\n", telement.c_str());
#else
dputsf(L"%s\n", telement.c_str());
#endif
}
} //lint !e529
//**************************************************************
// string compare routine, case-insensitive,
// wildcards are handled in the DOS fashion.
//**************************************************************
bool strcmpiwc(const TCHAR *onestr, const TCHAR *twostr)
{
char onechar, twochar ;
int k = 0 ;
while (LOOP_FOREVER) {
onechar = *(onestr+k) ;
twochar = *(twostr+k) ;
// if both are at end of string and no differences
// have been found, the strings are equal.
if (onechar == 0 && twochar == 0)
return true;
// if one string is at end and the other is not,
// there is NOT a match.
if (onechar == 0 || twochar == 0)
return false;
// at this point, neither char is NULL
// if either char is a 'match all' wildcard, the strings are equal
if (onechar == '*' || twochar == '*')
return true ;
if (onechar == '?' || twochar == '?') ; // match continues
else if (tolower(onechar) != tolower(twochar))
return false;
k++ ;
}
}
//***********************************************************
// DEBUG function: insert filespecs in display list
//***********************************************************
void insert_target_filespec(TCHAR *fstr)
{
target.emplace_back(fstr);
uint idx = target.size() - 1 ;
unsigned result = qualify(target[idx]) ;
if ((result & (QUAL_INV_DRIVE | QUAL_NO_PATH)) != 0) {
syslog(_T("qualify failed: %s\n"), target[idx].c_str());
error_exit(INV_DRIVE, (TCHAR *)target[idx].c_str()) ;
}
}
//********************************************************
// DELETE DUPLICATE FILESPECS from target array.
// Delete record if no differences found.
// Compare file and ext separately.
// This routine uses selection sort, because the list
// usually only has a couple of items in it.
//********************************************************
static void check_for_duplicate_targets(void)
{
unsigned idxHead, idxTail ;
unsigned ltcount = target.size() ;
// dump_target(_T("target(s) input\n"));
// head index should iterate over all elements *except* the last one,
// since the last element in list would not have any others to compare against.
for (idxHead=0 ; idxHead< (ltcount - 1) ; idxHead++) {
// tail index should iterate over all elements after
// the current head index.
// Note that the number of elements in the list may vary
// as items are deleted by this operation.
for (idxTail=idxHead+1 ; idxTail < ltcount ; idxTail++) {
try_next_tail:
// Scan file name and extension for equality.
// If both filename and extension are equal, delete one.
// if (target[idxHead].compare(target[idxTail]) == 0) {
if (target[idxHead] == target[idxTail]) {
target.erase(target.begin()+idxTail) ;
ltcount-- ;
// we don't want to increment idxTail after deleting element;
// it is now pointing to the next element in array
if (idxTail < ltcount) {
goto try_next_tail ;
}
}
}
} //lint !e850 for loop index variable 'j' whose type category is 'integral' is modified in body of the for loop that began at 'line 206'
// dump_target(_T("targets(s) filtered\n"));
// syslog(_T("target size: %u elements\n"), target.size());
}
/**********************************************************************/
/** File listing routines **/
/**********************************************************************/
static void process_filespecs(void)
{
TCHAR * strptr ;
unsigned j;
size_t slen ;
// handle single filespec
if (target.size() == 1 && !n.exec_only) {
start = finish = 0 ;
// in lfn format, convert /3 to /4
if (columns == 3) {
columns = 4 ;
}
// Extract base path from first filespec,
// and strip off filename
// _tcscpy(base_path, target[start].c_str()) ;
// strptr = _tcsrchr(base_path, '\\') ;
// if (strptr != 0) {
// strptr++ ; //lint !e613 skip past backslash, to filename
// *strptr = 0 ; // strip off filename
// }
// base_len = _tcslen(base_path) ;
base_path = target[start] ;
slen = base_path.find_last_of(L'\\');
if (slen != std::wstring::npos) {
slen++ ;
base_path.resize(slen);
}
// base_len = base_path.length() ;
//**************************************************
get_disk_info((TCHAR *) base_path.c_str()) ;
file_listing() ;
}
// handle multiple filespecs
else {
int temp_columns = columns ;
start = 0 ;
while (LOOP_FOREVER) {
// Extract base path from first filespec,
// and strip off filename
// in lfn format, convert /3 to /4
if (columns == 3) {
columns = 4 ;
}
// Extract base path from first filespec,
// and strip off filename
// _tcscpy(base_path, target[start].c_str()) ;
// strptr = _tcsrchr(base_path, '\\') ;
// if (strptr != 0) {
// strptr++ ; // skip past backslash, to filename
// *strptr = 0 ; // strip off filename
// }
// base_len = _tcslen(base_path) ;
base_path = target[start] ;
slen = base_path.find_last_of(L'\\');
if (slen != std::wstring::npos) {
slen++ ;
base_path.resize(slen);
}
// base_len = base_path.length() ;
//**************************************************
get_disk_info((TCHAR *) base_path.c_str()) ;
// seek out all other filespecs with same path
// This block sets variable 'finish'
j = start ;
j++ ;
while (LOOP_FOREVER) {
// if (j >= tcount) {
if (j >= target.size()) {
finish = j-1 ;
break;
}
// strip filename from next argument
_tcscpy(tempstr, target[j].c_str()) ;
strptr = _tcsrchr(tempstr, '\\') ; //lint !e613
strptr++ ;
*strptr = 0 ;
// now see if they are equal
if (_tcscmp(base_path.c_str(), tempstr) != 0) {
finish = j-1 ;
break;
}
j++ ;
}
check_for_duplicate_targets();
//**************************************************
// delete contents of existing file list
//**************************************************
clear_existing_file_list();
//**************************************************
file_listing() ;
// this block set variable 'start'
start = finish + 1 ;
if (start >= target.size())
break;
ncrlf() ;
columns = temp_columns ;
} // while not done
} // if multiple filespecs are present
} //lint !e533
//**************************************************
bool const comp(std::wstring const &a, std::wstring const &b)
{
// warning: Method called on moved-from object of type 'std::basic_string' [clang-analyzer-cplusplus.Move]
// Comments from Claude.AI, 08/06/26
// Good news — you've hit a well-documented false positive, not a real bug.
// This is tracked upstream as LLVM issue #78132
// https://github.com/llvm/llvm-project/issues/78132
return (a.compare(b) < 0) ; // NOLINT(clang-analyzer-cplusplus.Move)
}
//**************************************************
// Sort filespecs alphabetically,
// to group those in one directory.
//**************************************************
static void sort_target_paths(void)
{
std::sort(target.begin(), target.end(), comp);
}
//********************************************************************************
// this solution is from:
// https://github.com/coderforlife/mingw-unicode-main/
//********************************************************************************
#if defined(__GNUC__) && defined(_UNICODE)
#ifndef NOMAKEDEPEND
#ifndef __MSVCRT__
#error Unicode main function requires linking to MSVCRT
#endif
#endif
#include <wchar.h>
#include <stdlib.h>
extern int _CRT_glob;
extern
#ifdef __cplusplus
"C"
#endif
void __wgetmainargs(int*,wchar_t***,wchar_t***,int,int*); // NOLINT
#ifdef MAIN_USE_ENVP
int wmain(int argc, wchar_t *argv[], wchar_t *envp[]);
#else
int wmain(int argc, wchar_t *argv[]);
#endif
int main() // NOLINT
{
wchar_t **enpv, **argv;
int argc, si = 0;
__wgetmainargs(&argc, &argv, &enpv, _CRT_glob, &si); // this also creates the global variable __wargv
#ifdef MAIN_USE_ENVP
return wmain(argc, argv, enpv);
#else
return wmain(argc, argv);
#endif
}
#endif //defined(__GNUC__) && defined(_UNICODE)
//*****************************************************************
#ifdef UNICODE
int wmain(int argc, WCHAR **argv)
#else
int main(int argc, char **argv)
#endif
{
console_init(Version) ;
//***********************************************************
// Check for NDIR environment variable
//***********************************************************
// get program filename
int startIdx = 1 ;
TCHAR exename[MAX_PATH_LEN] ;
// [clang] _WIN32_WINNT: 0x0601
// [cygwin] _WIN32_WINNT: 0x0A00
// syslog(_T("_WIN32_WINNT: 0x%04X\n"), _WIN32_WINNT);
// interesting lessons from WinNT 4.0:
// If the OS is WinNT 4.0, and;
// If the executable file is located in the current directory,
// THEN:
// argv[0] does NOT contain the fully-qualified
// path of the EXE, it *only* contains the EXE name.
// In all other situations, argv[0] is fully qualified!!
//
// P.S. While we're here, derive default INI filename also
// printf("argv0=%s\n", argv[0]) ;
TCHAR* strptr = _tcsrchr(argv[0], _T('\\')) ;
// no path present
if (strptr == 0) {
SearchPath(NULL, argv[0], _T(".exe"), MAX_PATH_LEN, ininame, NULL) ;
strptr = _tcsrchr(ininame, _T('\\')) ;
if (strptr != 0)
_tcscpy(strptr, _T("\\ndir.ini")) ;
_tcscpy(exename, argv[0]) ;
// ininame[0] = 0 ; // ONLY support current location
}
else {
// pick up INI filename
_tcscpy(ininame, argv[0]) ;
strptr = _tcsrchr(ininame, _T('\\')) ;
if (strptr == 0)
return 1;
_tcscpy(strptr, _T("\\ndir.ini")) ;
// now process exe name for getenv()
strptr++ ; //lint !e613: skip backslash
_tcscpy(exename, strptr) ; //lint !e613
strptr = _tcschr(exename, _T('.')) ;
if (strptr != 0) {
*strptr = 0 ; // strip the extension
}
}
TCHAR* options = _tgetenv(exename) ;
if (options != 0) {
argv[0] = options ;
startIdx = 0 ;
}
//***********************************************************
// first read default settings
//***********************************************************
read_config_file() ;
//***********************************************************
// override defaults with command line and environment vars
//***********************************************************
parse_command_args(startIdx, argc, argv) ;
verify_flags() ; // this may add extensions if -x is given
//***********************************************************
// Execute the requested command
//***********************************************************
display_logo() ;
if (n.help) {
info(helptxt) ;
}
else if (n.info) {
info(idtxt) ;
}
else if (n.drive_summary > DSUMMARY_NONE) {
display_drive_summary() ;
}
else {
// If no filespec was given, insert current path with *.*
// if (target.size() == 0) {
if (target.empty()) {
insert_target_filespec(_T(".")) ;
}
sort_target_paths() ;
//***********************************************************************
// when tree listing is selected, it is assumed that each specified
// argument is a separate path, and that no wildcards nor specific
// filenames were provided.
// If such anomalies are presented, unpredictable results will occur.
//***********************************************************************
if (n.tree != eTreeForm::TREE_UNUSED) {
tree_listing(target.size()) ;
}
else {
process_filespecs() ;
}
}
error_exit(DATA_OKAY, NULL) ;
return 0 ;
}