xref: /original-bsd/usr.bin/whereis/whereis.c (revision 27393bdf)
1 /*-
2  * Copyright (c) 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char copyright[] =
10 "@(#) Copyright (c) 1993\n\
11 	The Regents of the University of California.  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)whereis.c	8.2 (Berkeley) 04/27/95";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/stat.h>
20 #include <sys/sysctl.h>
21 
22 #include <err.h>
23 #include <errno.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 
28 void usage __P((void));
29 
30 int
31 main(argc, argv)
32 	int argc;
33 	char *argv[];
34 {
35 	struct stat sb;
36 	size_t len;
37 	int ch, sverrno, mib[2];
38 	char *p, *t, *std, path[MAXPATHLEN];
39 
40 	while ((ch = getopt(argc, argv, "")) != EOF)
41 		switch (ch) {
42 		case '?':
43 		default:
44 			usage();
45 		}
46 	argc -= optind;
47 	argv += optind;
48 
49 	if (argc == 0)
50 		usage();
51 
52 	/* Retrieve the standard path. */
53 	mib[0] = CTL_USER;
54 	mib[1] = USER_CS_PATH;
55 	if (sysctl(mib, 2, NULL, &len, NULL, 0) == -1)
56 		return (-1);
57 	if (len == 0)
58 		err(1, "user_cs_path: sysctl: zero length\n");
59 	if ((std = malloc(len)) == NULL)
60 		err(1, NULL);
61 	if (sysctl(mib, 2, std, &len, NULL, 0) == -1) {
62 		sverrno = errno;
63 		free(std);
64 		errno = sverrno;
65 		err(1, "sysctl: user_cs_path");
66 	}
67 
68 	/* For each path, for each program... */
69 	for (; *argv; ++argv)
70 		for (p = std;; *p++ = ':') {
71 			t = p;
72 			if ((p = strchr(p, ':')) != NULL) {
73 				*p = '\0';
74 				if (t == p)
75 					t = ".";
76 			} else
77 				if (strlen(t) == 0)
78 					t = ".";
79 			(void)snprintf(path, sizeof(path), "%s/%s", t, *argv);
80 			if (!stat(path, &sb))
81 				(void)printf("%s\n", path);
82 			if (p == NULL)
83 				break;
84 		}
85 }
86 
87 void
88 usage()
89 {
90 
91 	(void)fprintf(stderr, "usage: whereis program [...]\n");
92 	exit (1);
93 }
94