echo: Added echo
[mutos-utils.git] / basename.c
blobac9e022e8dc26eeab91e2cf206fa1a333fc8ef10
1 /*
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.
15 #include <stdio.h>
16 #include <string.h>
18 #define VERSION "0.01"
20 int main(int argc, char* argv[])
23 // flag parsing
24 int arg = 0;
25 for (arg = 1; arg < argc; arg++)
27 if (strcmp("--help", argv[arg]) == 0 || strcmp("-h", argv[arg]) == 0) {
28 printf("Usage: %s [name] [suffix]\n", argv[0]);
29 printf("\n"
30 " --help Print this message.\n"
31 " --version Show version info.\n");
32 return 0;
33 } else if (strcmp("--version", argv[arg]) == 0 || strcmp("-v", argv[arg]) == 0) {
34 printf("basename (mutos) v"VERSION"\n");
35 return 0;
36 } else {
37 break;
41 if ((argc - arg) == 0) {
42 fprintf(stderr, "%s: missing operand\n"
43 "Run '%s --help' for usage.\n",
44 argv[0], argv[0]);
45 return 1;
46 } else if ((argc - arg) > 2) {
47 fprintf(stderr, "%s: too many arguments\n",
48 argv[0]);
49 return 1;
52 char* name = argv[arg];
53 char* suffix = NULL;
55 // remove any trailing slashes
56 for (size_t i = strlen(name) - 1; ; i--)
58 if (name[i] == '/') {
59 name[i] = '\0';
60 } else {
61 // if there's no more slashes
62 break;
65 // reached the beginning of the string
66 if (i == 0) {
67 break;
71 if ((argc - arg) == 2) {
72 suffix = argv[arg + 1];
74 for (size_t i = strlen(name), j = strlen(suffix); ; i--, j--)
76 if (name[i - 1] == suffix[j - 1]) {
77 name[i - 1] = '\0';
78 } else {
79 break;
84 // set start to zero, so that if no slash is found,
85 // the start location is the beginning of the string
86 size_t start = 0;
87 for (size_t i = strlen(name) - 1; ; i--)
89 if (name[i] == '/') {
90 start = i + 1;
91 break;
94 // reached the beginning of the string
95 if (i == 0) {
96 break;
100 for (size_t i = start; i < strlen(name); i++)
102 printf("%c", name[i]);
105 // if suffix deleted the entire basename,
106 // print the whole basename instead of
107 // nothing
108 if (start == strlen(name)) {
109 printf("%s", suffix);
111 printf("\n");
113 return 0;