2 Copyright © 2013 Alastair Stuart
4 This program is open source 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 3 of the License, or
7 (at your option) 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.
18 #define VERSION "0.01"
20 int main(int argc
, char* argv
[])
24 for (arg
= 1; arg
< argc
; arg
++)
26 if (strcmp("--help", argv
[arg
]) == 0 || strcmp("-h", argv
[arg
]) == 0) {
27 printf("Usage: %s [name] [suffix]\n", argv
[0]);
29 " --help Print this message.\n"
30 " --version Show version info.\n");
32 } else if (strcmp("--version", argv
[arg
]) == 0 || strcmp("-v", argv
[arg
]) == 0) {
33 printf("basename (mutos) v"VERSION
"\n");
35 } else if (strcmp(argv
[arg
], "--") == 0) {
43 if ((argc
- arg
) == 0) {
44 fprintf(stderr
, "%s: missing operand\n"
45 "Run '%s --help' for usage.\n",
48 } else if ((argc
- arg
) > 2) {
49 fprintf(stderr
, "%s: too many arguments\n",
54 char* name
= argv
[arg
];
57 // check if string consists entirely of slash characters
58 for (size_t i
= 0; i
< strlen(name
); i
++)
64 if (name
[i
] == '/' && i
== strlen(name
) - 1) {
70 // remove any trailing slashes
71 for (size_t i
= strlen(name
) - 1; ; i
--)
76 // if there's no more slashes
80 // reached the beginning of the string
86 // trim suffix (if there is one)
87 if ((argc
- arg
) == 2) {
88 suffix
= argv
[arg
+ 1];
90 for (size_t i
= strlen(name
), j
= strlen(suffix
); ; i
--, j
--)
92 if (name
[i
- 1] == suffix
[j
- 1]) {
100 // find the first slash
102 for (size_t i
= strlen(name
) - 1; ; i
--)
104 if (name
[i
] == '/') {
109 // reached the beginning of the string
116 // if suffix deleted the entire basename,
117 // print the whole basename instead of
119 if (strlen(name
+start
) == 0) {
120 printf("%s", suffix
);
122 printf("%s", name
+start
);