Merged changes made for version 4.1.20 onto the trunk
[findutils.git] / lib / nextelem.c
blob7df312b973bb30006b855be67112477ee922c02e
1 /* Return the next element of a path.
2 Copyright (C) 1992 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 9 Temple Place - Suite 330, Boston, MA 02111-1307,
17 USA.
20 /* Written by David MacKenzie <djm@gnu.ai.mit.edu>,
21 inspired by John P. Rouillard <rouilj@cs.umb.edu>. */
23 #ifdef HAVE_CONFIG_H
24 #include <gnulib/config.h>
25 #undef VERSION
26 #undef PACKAGE_VERSION
27 #undef PACKAGE_TARNAME
28 #undef PACKAGE_STRING
29 #undef PACKAGE
30 #undef PACKAGE_NAME
31 #include <config.h>
32 #endif
34 #include <stdio.h>
35 #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
36 #include <string.h>
37 #else
38 #include <strings.h>
39 #ifndef strchr
40 #define strchr index
41 #endif
42 #endif
43 #if defined(STDC_HEADERS)
44 #include <stdlib.h>
45 #endif
47 /* Return the next element of a colon-separated path.
48 A null entry in the path is equivalent to "." (the current directory).
50 If NEW_PATH is non-NULL, set the path and return NULL.
51 If NEW_PATH is NULL, return the next item in the string, or
52 return NULL if there are no more elements. */
54 char *
55 next_element (new_path)
56 char *new_path;
58 static char *path = NULL; /* Freshly allocated copy of NEW_PATH. */
59 static char *end; /* Start of next element to return. */
60 static int final_colon; /* If zero, path didn't end with a colon. */
61 char *start; /* Start of path element to return. */
63 if (new_path)
65 if (path)
66 free (path);
67 end = path = strdup (new_path);
68 final_colon = 0;
69 return NULL;
72 if (*end == '\0')
74 if (final_colon)
76 final_colon = 0;
77 return ".";
79 return NULL;
82 start = end;
83 final_colon = 1; /* Maybe there will be one. */
85 end = strchr (start, ':');
86 if (end == start)
88 /* An empty path element. */
89 *end++ = '\0';
90 return ".";
92 else if (end == NULL)
94 /* The last path element. */
95 end = strchr (start, '\0');
96 final_colon = 0;
98 else
99 *end++ = '\0';
101 return start;
104 #ifdef TEST
106 main ()
108 char *p;
110 next_element (getenv ("PATH"));
111 while (p = next_element (NULL))
112 puts (p);
113 exit (0);
115 #endif /* TEST */