File: redexp.vms

package info (click to toggle)
jgraph 83-19
  • links: PTS
  • area: main
  • in suites: woody
  • size: 624 kB
  • ctags: 445
  • sloc: ansic: 4,728; makefile: 186; sh: 106; awk: 104
file content (526 lines) | stat: -rw-r--r-- 19,252 bytes parent folder | download | duplicates (6)
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
/*	--redexp.vms--
   This 'C' module may be included prior to the ``main'' programs on VMS in
   order to allow 'C' arguments to contain redirection symbols (<,>,>>) and
   VMS wild cards (*,%, ...], [-).  By including this module, two programs
   redirect() and expand() are run prior to turning control over to
   your main() entry point.

    redirect-- Gregg Townsend circa 1983,
    expand-- John Campbell circa 1987

   This code is public domain, others may use it freely. Credit, however, to
   Gregg Townsend (who wrote ``redirect()'') and John Campbell (who followed
   with ``expand()'') would be appreciated.  If someone writes the next
   logical successor ``pipe()'', please email a copy to
   ...!arizona!naucse!jdc (John Campbell) (Gregg works on unix :-).

   HISTORY

*/

#include <rms.h>      /* No easy way to tell if this has already been included. */
#ifndef ERANGE
#include <stdlib.h>   /* Include only if missing. */
#endif
#ifndef __FILE
#include <stdio.h>    /* Include only if missing. */
#endif
#include <ctype.h>  /* Added for conversion to lower case  */
#ifndef __STRING_LOADED
#include <string.h>
#endif /* !__STRING_LOADED */

/* Expansion of wild cards is done using RMS. */
        struct NAMBLK { struct NAM nam;         /* VMS nam block structure */
                 char es[NAM$C_MAXRSS],         /* Extended string         */
                      rs[NAM$C_MAXRSS];         /* Resultant string        */
               };

#define ErrorExit 1

/* Allow the user to override _N_FARGS or _E_FLAG if they wish. */
#ifndef _N_FARGS
#define _N_FARGS 0 /* no automatic redirection please */
#endif
#ifndef _E_FLAG
#define _E_FLAG 4  /* only include dev and dir if different from default */
#endif
/*
   Since the following will possibly be included in a single module, try
   hard to avoid name conflicts. (Just being static doesn't cut it if
   compiled in the same module.)
*/
#define redirect     _r_edirect
#define filearg      _f_ilearg
#define expand       _e_xpand
#define wild_found   _w_ild_found
#define wild_expand  _w_ild_expand

/* forward protypes */
static void redirect(int *argc, char *argv[], int nfargs);
char **expand (int *argc, const char *argv[], const int flag);

main(int argc, char *argv[], char *envp[])
{
   redirect (&argc, argv, _N_FARGS);
   argv = expand (&argc, argv, _E_FLAG);

   /* Make the user's main entry point this routine's entry point. */
#define main _user_main
   _user_main (argc, argv, envp);
}

/* ------------------------ REDIRECT code ------------------------ */

/*
 * redirect(&argc,argv,nfargs) - redirect standard I/O
 *    int *argc         number of command arguments (from call to main)
 *    char *argv[]      command argument list (from call to main)
 *    int nfargs        number of filename arguments to process
 *
 * argc and argv will be adjusted by redirect.
 *
 * redirect processes a program's command argument list and handles redirection
 * of stdin, and stdout.  Any arguments which redirect I/O are removed from the
 * argument list, and argc is adjusted accordingly.  redirect would typically be
 * called as the first statement in the main program.
 *
 * Files are redirected based on syntax or position of command arguments.
 * Arguments of the following forms always redirect a file:
 *
 *    <file     redirects standard input to read the given file
 *    >file     redirects standard output to write to the given file
 *    >>file    redirects standard output to append to the given file
 *
 * It is often useful to allow alternate input and output files as the
 * first two command arguments without requiring the <file and >file
 * syntax.  If the nfargs argument to redirect is 2 or more then the
 * first two command arguments, if supplied, will be interpreted in this
 * manner:  the first argument replaces stdin and the second stdout.
 * A filename of "-" may be specified to occupy a position without
 * performing any redirection.
 *
 * If nfargs is 1, only the first argument will be considered and will
 * replace standard input if given.  Any arguments processed by setting
 * nfargs > 0 will be removed from the argument list, and again argc will
 * be adjusted.  Positional redirection follows syntax-specified
 * redirection and therefore overrides it.
 *
 */

/* forward prototype for local routine */
static void filearg(int *argc, char *argv[], int n, int i, FILE *fp, char mode[]);

static void redirect(int *argc, char *argv[], int nfargs)
{
   int i;

   i = 1;
   while (i < *argc)  {         /* for every command argument... */
      switch (argv[i][0])  {            /* check first character */
         case '<':                      /* <file redirects stdin */
            filearg(argc,argv,i,1,stdin,"r");
            break;
         case '>':                      /* >file or >>file redirects stdout */
            if (argv[i][1] == '>')
               filearg(argc,argv,i,2,stdout,"a");
            else
               filearg(argc,argv,i,1,stdout,"w");
            break;
         default:                       /* not recognized, go on to next arg */
            i++;
      }
   }
   if (nfargs >= 1 && *argc > 1)        /* if positional redirection & 1 arg */
      filearg(argc,argv,1,0,stdin,"r"); /* then redirect stdin */
   if (nfargs >= 2 && *argc > 1)        /* likewise for 2nd arg if wanted */
      filearg(argc,argv,1,0,stdout,"w");/* redirect stdout */
}

/* local routine for redirect() */
/* filearg(&argc,argv,n,i,fp,mode) - redirect and remove file argument
 *    int *argc         number of command arguments (from call to main)
 *    char *argv[]      command argument list (from call to main)
 *    int n             argv entry to use as file name and then delete
 *    int i             first character of file name to use (skip '<' etc.)
 *    FILE *fp          file pointer for file to reopen (typically stdin etc.)
 *    char mode[]       file access mode (see freopen spec)
 */

static void filearg(int *argc, char *argv[], int n, int i, FILE *fp, char mode[])
{
   if (strcmp(argv[n]+i,"-"))           /* alter file if arg not "-" */
      fp = freopen(argv[n]+i,mode,fp,"mbf=8","mbc=16");
   if (fp == NULL)  {                   /* abort on error */
      fprintf(stderr,"%%can't open %s",argv[n]+i);
      exit(ErrorExit);
   }
   for ( ;  n < *argc;  n++)            /* move down following arguments */
      argv[n] = argv[n+1];
   *argc = *argc - 1;                   /* decrement argument count */
}

/* ------------------------ EXPAND code ------------------------ */
/*-
   ``expand()'' is a routine to expand wild-cards to file specifications.
   This routine is often used in conjunction with ``redirect()'' to provide
   both wild card expansion and standard file redirection prior to doing
   any real work in a 'C' program.

   Normal usage is to include the following line prior to using argc or
   argv in main():

     argv = expand (&argc, argv, 0);

   ``argc'' will be adjusted by ``expand()'', the return value from expand
   will replace ``argv''.

   ``expand()'' processes a program's command argument list and expands any
   wild cards into zero or more argv entries. Only arguments that posses VMS
   wild-cards are expanded. Wild cards searched for are ``*'', ``%'',
   ``...]'', and ``[-''. If the wild-card is found inside a single or double
   quote ("*" or '%') then they are not counted as wild-cards. Be aware that
   the expansion of a VMS wild card will match all VMS files, including
   directory files (".DIR;1").

   NOTE: The use of quotes in VMS requires thinking about how the CLI expands
   things before handing the argument line over to your program.  Do not
   expect "*" to avoid expansion, use """*""" instead.  Likewise, expression
   substitution precludes the use of (') to quote wild cards:
           $ A := HELLO
           $ ECHO 'a'   ! 'C' program that calls ``expand()''
           hello
   The easiest way to escape a wild-card may be "'*'".  The point is that
   ``expand()'' will only recognize quotes passed into main().
   Note: I have added '\' as an escape character -hdd.

   ``expand()'' references the VMS runtime routines, you will need to
   link with the 'C' RTL whenever expand is used.

   Parameters:

         argc:  Pointer to the number of command arguments (from main),
                the contents of this parameter are modified.

         argv:  Pointer to the initial command argument list (from main),
                the contents are copied into a new array which is returned
                from this routine.

         flag:  Flag indicating how to expand wild-cards:
                   0 - Complete file name expansion
                   1 - only file name (no directory or version).
                   2 - directory info and file name (no version).
                   3 - file name and version info (no directory).
		   4 - omit fields that are the same as RMS default.
 -*/

/* Local prototypes. */
int wild_found (char *string);
char **wild_expand (const char *string, char **argv, int *argc,
                    int extra, int flag);
/*
   General note: removing the prototyping and const keywords should
   allow this code to compile with VMS 'C' compilers prior to version
   2.3-024.
*/

char **expand (int *argc, const char *argv[], const int flag)
{
   int i, nargc;
   char **nargv;
   char *s1;

   /* Get an initial amount of memory for the master nargv array. */
   if ((nargv = (char **)malloc ((*argc+1) * sizeof (char *))) == NULL) {
      fprintf (stderr, "Not enough memory to expand argument list\n");
      exit (ErrorExit);
   }
   /* Copy the command name (0th argument), but only the name of the exe */
   nargv[0] = strchr(argv[0],']');
   if (nargv[0] != NULL) {
       nargv[0]++;
       if ((s1=strrchr(nargv[0],'.')) != NULL) *s1 = '\0';
   } else {
       nargv[0] = argv[0];	/* if nothing suitable take original */
   }      

   /* Copy all other arguments, expanding those that have wild characters. */
   for (nargc = i = 1; i < *argc; i++) {
      if (wild_found(argv[i]))
         nargv = wild_expand(argv[i], nargv, &nargc, *argc-i, flag);
      else
         nargv[nargc++] = argv[i];
   }
   *argc = nargc;
   nargv[nargc] = NULL;  /* realloc always 0 fills, but... */

   return nargv;
}

static int wild_found (char *string)
/*
   Routine to search the given string for a VMS wild-card pattern.
   Returns 1 if "*", "%", "[-", or "...]" is found.  (This may not
   be all VMS wild-cards but it is enough for now--anyone that wants
   to recognize others can change this code.)

   Parameter:

      string: '\0' terminated character array.
*/
{
   int state = 0;

   /* State of 0 is "rest" state.  State 1 on our way to [-, states 2-4
      on our way to ...], negative states indicate the two quotes (' -10,
      " -1).
   */
   for ( ;*string; string++) {
      switch (*string) {
      case '*':
      case '%':
         if (state >= 0)
            return 1;                    /* Unquoted % or * found. */
      break;
      case '[':
         if (state >= 0)
            state = 1;
      break;
      case ']':
         if (state == 4)
            return 1;                    /* Unquoted ...] found. */
         else if (state >= 0)
            state = 0;
      break;
      case '-':
         if (state == 1)
            return 1;                    /* Unquoted [- found. */
         else if (state >= 0)
            state = 0;
      break;
      case '.':
         if (state == 1 || state == 0)
            state = 2;                   /* First '.' */
         else if (state > 1 && state < 5)
            state++;                     /* ... == states 2, 3, 4 */
         else if (state >= 0)
            state = 0;
      break;
      case '\'':
         if (state <= -10)
            state += 10;           /* One ', possibly one " also */
         else if (state < 0)
            state -= 10;           /* 0 ', possibly one " */
         else
            state = -10;           /* No ' or " prior to this ' */
      break;
      case '"':
         if (state == -11)
            state = -10;           /* Both " and ' prior to this. */
         else if (state == -10)
            state = -11;           /* A ' prior to this. */
         else if (state == -1)
            state = 0;             /* A " prior to this. */
         else
            state = -1;            /* No ' or " prior to this " */
      break;
      case '\\':
         string = strcpy(string, string+1);
	 state = 0;
      break;
      }
   }
   return 0;
}


static char **wild_expand(const char *wild, char **argv,
			  int *argc, int extra, int flag)
/*
   Routine to expand wild into new arguments appended to the end
   of argv[*argc].  This routine must realloc in order to make room
   for the individual arguments and malloc for enough space for each
   of the arguments.  The return value is a new **argv.

   Parameters:

         wild:  '\0' terminated string that needs to be expanded.

         argv:  initial starting address of the argv array.

         argc:  pointer to an integer that tells the current end of the
                argument list.

        extra:  The number of extra pointers that the returned argv
                must have available for future assignments.

         flag:  Flag indicating how to expand wild-card:
                  0 - Complete file name expansion
                  1 - only file name (no directory or version).
                  2 - directory info and file name (no version)
                  3 - file name and version info (no directory).
		  4 - omit fields that are the same as RMS default.
*/
{
   int more_to_go = 1, err, length, status, len_wild, i, ddev_l, ddir_l;
   char *namptr;
   struct FAB fab_blk;
   struct NAMBLK nam_blk;
   char path[256];
   char *ddevice = &path[0];	/* default device and directory */
   char *ddirectory, *ppath;

   char *env = getenv("PATH");
   ppath = &path[0];
   while (*env) {
       char *p = env++;
       if ((*ppath++ = _toupper(*p)) == ':') {
	   ddev_l = ppath - &path[0];
	   *ppath++ = 0;
	   ddirectory = ppath;
       }
   }
   *ppath++ = 0;
   ddir_l = ppath - ddirectory - 1;
   len_wild = strlen(wild);

   /* Initialize all the fab and nam fields needed for parse and search */

   fab_blk = cc$rms_fab;                   /* Initialize FAB structure */

   nam_blk.nam    = cc$rms_nam;            /* Initialize NAM structure */
   fab_blk.fab$l_dna = ".*";               /* Default file specif.     */
   fab_blk.fab$b_dns = 2;                  /* Length of default spec.  */
   fab_blk.fab$l_nam = &nam_blk.nam;       /* Set address of NAM in FAB*/
   nam_blk.nam.nam$b_ess = NAM$C_MAXRSS;   /* Set extended  string size*/
   nam_blk.nam.nam$l_esa = nam_blk.es;     /* and address              */
   nam_blk.nam.nam$b_rss = NAM$C_MAXRSS;   /* Set resultant string size*/
   nam_blk.nam.nam$l_rsa = nam_blk.rs;     /* and address              */
   nam_blk.nam.nam$l_rlf = NULL;           /* No related file address  */

   fab_blk.fab$l_fna = wild;           /* Address of file name string  */
   fab_blk.fab$b_fns = len_wild;       /* Length of file name string   */

   /* Prepare to enter the search loop, parse fab. */
   err = SYS$PARSE (&fab_blk);

   /* Catch the directory not found error and return no files found. */
   if (err != RMS$_NORMAL)
      exit(err);

   while (more_to_go) {
      err = SYS$SEARCH (&fab_blk);
      if (err == RMS$_NMF || err == RMS$_FNF)
         more_to_go = 0;               /* Done, no more files found */
      else if (err != RMS$_NORMAL)
         exit (err);
      else {
      /* Count that we now have this many arguments. */
         (*argc)++;

      /* Make sure there is room for a new pointer. */
         if ((argv = realloc (argv, (*argc + extra)*sizeof(char *))) == NULL) {
            fprintf (stderr, "Not enough memory to expand argument list\n");
            exit(ErrorExit);
         }

      /* Move the right name into the list. */
         switch (flag) {
         case 0:             /* Complete file name */
            length = nam_blk.nam.nam$b_rsl;
            namptr = nam_blk.rs;
            break;
         case 1:            /* File name only (no directory or version). */
            length = nam_blk.nam.nam$b_name + nam_blk.nam.nam$b_type;
            namptr = nam_blk.nam.nam$l_name;
            break;
         case 2:            /* directory and file name (no version) */
            length = nam_blk.nam.nam$b_rsl - nam_blk.nam.nam$b_ver;
            namptr = nam_blk.rs;
            break;
         case 3:            /* File name and version (no directory). */
            length = nam_blk.nam.nam$b_name +
                     nam_blk.nam.nam$b_type +
                     nam_blk.nam.nam$b_ver;
            namptr = nam_blk.nam.nam$l_name;
            break;
	 case 4:	     /* Remove redundant fields, no version */
            length = nam_blk.nam.nam$b_rsl - nam_blk.nam.nam$b_ver;
            namptr = nam_blk.rs;
	    if ((nam_blk.nam.nam$b_dev==ddev_l) &&
	    	!strncmp(namptr, ddevice, nam_blk.nam.nam$b_dev)) {
		    length -= nam_blk.nam.nam$b_dev;
		    namptr += nam_blk.nam.nam$b_dev;
		    if ((nam_blk.nam.nam$b_dir==ddir_l) &&
		    	!strncmp(namptr, ddirectory, nam_blk.nam.nam$b_dir)) {
			    length -= nam_blk.nam.nam$b_dir;
			    namptr += nam_blk.nam.nam$b_dir;
			}
		}
            break;
         default:
            fprintf (stderr, "illegal flag used in VMS expand call\n");
            exit (ErrorExit);
	 } /* end of switch */
	 /* Copy the requested string into the argument array. */
         if ((argv[*argc-1] = malloc (length+1)) == NULL) {
            fprintf (stderr, "Not enough memory to expand argument list\n");
            exit (ErrorExit);
	 }
         /* Copy the string, translate to lower case */
         /* strncpy (argv[*argc-1], namptr, length); */
         for (i=0; i<length; i++) {
	     argv[*argc-1][i] = _tolower(*namptr);
	     namptr++;
	 }
         /* End of modification */
         argv[*argc-1][length] = '\0';
      }
   } /* end while (more_to_go) */
   return (argv);
}

/* Remove all the defines that might affect the user's code. */

#undef redirect
#undef filearg
#undef expand
#undef wild_found
#undef wild_expand

#if 0
/* ------------------------ ECHO sample code ------------------------ */

#include <stdio.h>
/* here come the 3 lines that make this Unix program into a VMS one: */
#ifdef VMS
#include <redexp.vms>
#endif

/*
   This main program allows you to run experiments with redexp.vms.
   Try $ echo *.*, $ echo -f1 [-...]*.*, $ echo -f[0-3] *.*.
   Questions about using "%", "\", etc. may be answered by testing
   with this version of echo.

   To use this, cut from the "#if 0" above up to the last #endif,
   and put the text in echo.c. Assuming you have defined VAXC$INCLUDE
   to also look in the directory where you put redexp.VMS, you should
   be able to compile and link echo. Define a symbol echo as
   	echo :== $sys$disk:[]echo
   and you are ready to run.

*/
main(argc, argv)
int argc;
char *argv[];
{
    int i = 0;

    while (i < argc) {
	printf("argv[%d]: %s\n", i, argv[i]);
	i++;	
    }
}
/* ------------------------ ECHO sample code end --------------------- */
#endif  /* if 0 */