]> pd.if.org Git - pdutils/blob - posix/dirname/dirname.c
rename utils to posix
[pdutils] / posix / dirname / dirname.c
1 /*
2  * dirname.c - return the directory portion of a pathname
3  *
4  * Version: 2008-1.01
5  * Build:   c89 -o dirname dirname.c
6  * Source:  <http://pdcore.sourceforge.net/>
7  * Spec:    <http://www.opengroup.org/onlinepubs/9699919799/utilities/dirname.html>
8  *
9  * This is free and unencumbered software released into the public domain,
10  * provided "as is", without warranty of any kind, express or implied. See the
11  * file UNLICENSE and the website <http://unlicense.org> for further details.
12  */
13
14
15 #define _POSIX_SOURCE
16
17 #include <locale.h>
18 #include <stdio.h>
19
20 #define USAGE "usage: dirname string\n"
21
22
23 int main(int argc, char **argv)
24 {
25     char *head, *tail;
26
27     setlocale (LC_ALL, "");
28
29     if (argc != 2)
30     {
31         fprintf(stderr, USAGE);
32         return(1);
33     }
34
35     head = tail = argv[1];
36     while (*tail)
37         tail++;
38
39     while (tail > head && tail[-1] == '/')
40         tail--;
41     while (tail > head && tail[-1] != '/')
42         tail--;
43     while (tail > head && tail[-1] == '/')
44         tail--;
45
46     if (head == tail)
47         printf(*head == '/' ? "/\n" : ".\n");
48     else
49         printf("%.*s\n", (tail - head), head);
50
51     return(0);
52 }