xref: /illumos-gate/usr/src/cmd/refer/hunt7.c (revision d7c57852)
1 /*
2  * Copyright 2017 Gary Mills
3  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
4  * Use is subject to license terms.
5  */
6 
7 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
8 /*	  All Rights Reserved  	*/
9 
10 /*
11  * Copyright (c) 1980 Regents of the University of California.
12  * All rights reserved. The Berkeley software License Agreement
13  * specifies the terms and conditions for redistribution.
14  */
15 
16 #include <stdio.h>
17 #include <locale.h>
18 #include <assert.h>
19 #define	SAME 0
20 #define	FGCT 10
21 #define	FGSIZE 150
22 
23 int keepold = 1;	/* keep old things for fgrep search */
24 char fgspace[FGSIZE];
25 char *fgp = fgspace;
26 char *fgnames[FGCT];
27 char **fgnamp = fgnames;
28 
29 extern char *mindex();
30 
31 long
findline(char * in,char ** out,int outlen,long indexdate)32 findline(char *in, char **out, int outlen, long indexdate)
33 {
34 	static char name[100] = "";
35 	char *p, **ftp;
36 	extern long gdate();
37 	static FILE *fa = NULL;
38 	long lp, llen;
39 	int k, nofil;
40 
41 	if (mindex(in, '!'))
42 		return (0);
43 
44 	nofil = in[0] == 0;
45 	for (p = in; *p && *p != ':' && *p != ';'; p++)
46 		;
47 	if (*p) *p++ = 0;
48 	else p = in;
49 	k = sscanf(p, "%ld,%ld", &lp, &llen);
50 	if (k < 2) {
51 		lp = 0;
52 		llen = outlen;
53 	}
54 	if (nofil) {
55 		fa = stdin;
56 	} else
57 		if (strcmp(name, in) != 0 || 1) {
58 			if (fa != NULL)
59 				fa = freopen(in, "r", fa);
60 			else
61 				fa = fopen(in, "r");
62 			if (fa == NULL)
63 				return (0);
64 			/* err("Can't open %s", in); */
65 			strcpy(name, in);
66 			if (gdate(fa) > indexdate && indexdate != 0) {
67 				if (keepold) {
68 					for (ftp = fgnames; ftp < fgnamp; ftp++)
69 						if (strcmp(*ftp, name) == SAME)
70 							return (0);
71 					strcpy(*fgnamp++ = fgp, name);
72 					assert(fgnamp < fgnames+FGCT);
73 					while (*fgp && *fgp != ':')
74 						fgp++;
75 					*fgp++ = 0;
76 					assert(fgp < fgspace+FGSIZE);
77 					return (0);
78 				}
79 				fprintf(stderr, gettext(
80 				    "Warning: index predates file '%s'\n"),
81 				    name);
82 			}
83 		}
84 	if (fa != NULL) {
85 		fseek(fa, lp, 0);
86 		*out = (char *)malloc(llen + 1);
87 		if (*out == NULL) {
88 			return (0);
89 		}
90 		(void) fread(*out, 1, llen, fa);
91 		*(*out + llen) = 0;
92 	}
93 	return (llen);
94 }
95