mv: Added mv
[mutos-utils.git] / basename.c
bloba0cb0df56263061eaf6b0c42fc4e57f5efdb8757
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[])
22 // flag parsing
23 int arg = 0;
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]);
28 printf("\n"
29 " --help Print this message.\n"
30 " --version Show version info.\n");
31 return 0;
32 } else if (strcmp("--version", argv[arg]) == 0 || strcmp("-v", argv[arg]) == 0) {
33 printf("basename (mutos) v"VERSION"\n");
34 return 0;
35 } else if (strcmp(argv[arg], "--") == 0) {
36 arg++;
37 break;
38 } else {
39 break;
43 if ((argc - arg) == 0) {
44 fprintf(stderr, "%s: missing operand\n"
45 "Run '%s --help' for usage.\n",
46 argv[0], argv[0]);
47 return 1;
48 } else if ((argc - arg) > 2) {
49 fprintf(stderr, "%s: too many arguments\n",
50 argv[0]);
51 return 1;
54 char* name = argv[arg];
55 char* suffix = NULL;
57 // check if string consists entirely of slash characters
58 for (size_t i = 0; i < strlen(name); i++)
60 if (name[i] != '/') {
61 break;
64 if (name[i] == '/' && i == strlen(name) - 1) {
65 printf("/\n");
66 return 0;
70 // remove any trailing slashes
71 for (size_t i = strlen(name) - 1; ; i--)
73 if (name[i] == '/') {
74 name[i] = '\0';
75 } else {
76 // if there's no more slashes
77 break;
80 // reached the beginning of the string
81 if (i == 0) {
82 break;
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]) {
93 name[i - 1] = '\0';
94 } else {
95 break;
100 // find the first slash
101 size_t start = 0;
102 for (size_t i = strlen(name) - 1; ; i--)
104 if (name[i] == '/') {
105 start = i + 1;
106 break;
109 // reached the beginning of the string
110 if (i == 0) {
111 start = i;
112 break;
116 // if suffix deleted the entire basename,
117 // print the whole basename instead of
118 // nothing
119 if (strlen(name+start) == 0) {
120 printf("%s", suffix);
121 } else {
122 printf("%s", name+start);
124 printf("\n");
126 return 0;