argv ==> stdin (fast)

Jim Bigelow jimbi at copper.UUCP
Tue Dec 2 04:23:40 AEST 1986


In article <2972 at rsch.WISC.EDU>, mcvoy at rsch.WISC.EDU (Lawrence W. McVoy) writes:
> Hi there.  I'm using lex & yacc to do some work for me and I can't 
> quite get it.   The scanner & parser part works, but only if it's 
> getting input from stdin.  I diddled lex.yy.c to change the getc(yyin)
> call in the input() define to call my routine which feed sit characters 
> from argv.  This works if I call yylex() from main, but if yyparse calls 

One method I haven't seen posted yet is to fopen a file name from argv and 
give yyin the value:

/* 
 *	main -- read command line params, open/process/close files
 */
#include <stdio.h>

extern FILE *yyin;		/* input to lexical analyzer */
extern char *func_name;

extern char *optarg;		/* used and set by getopt */
extern int optind; opterr;

int Debug = 0;			/* debug flag */
int Verbose = 0;		/* verbose flag */

usage(name)
	char *name;
{
	printf("Usage: %s [-lnv] func_name [file...]\n", name);
}

main (argc, argv) 
	int argc;
	char **argv;
{
	int c;

	while((c = getopt(argc, argv, "lnvdp:")) != EOF)
		switch(c) {
		case 'v':
			Verbose = 1;
			break;
		case 'd':
			Debug = 1;
			break;	
		case '?':
			usage(argv[0]);
			exit(1);
			break;
		}

	if(optind == argc)
		yylex();
	else 
		for(; optind < argc; optind++) {
			if(( yyin = fopen(argv[optind], "r"))== NULL) {
				printf("%s: cannot open %s\n",argv[0], argv[optind]);
			} else {
				yylex();
				fclose(yyin);
			}
		}
}



More information about the Comp.lang.c mailing list