wc: Added wc
[mutos-utils.git] / dirname.c
blobabba9862ced78d0e0bfcb2bc74bc8bb105405306
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 if (argc < 2) {
23 printf("%s: missing operand\n"
24 "Run '%s --help' for usage.\n",
25 argv[0], argv[0]);
26 return 1;
29 char sep = '\n';
31 // flag parsing
32 int arg = 0;
33 for (arg = 1; arg < argc; arg++)
35 if (strcmp(argv[arg], "-z") == 0 || strcmp(argv[arg], "--zero") == 0) {
36 sep = '\0';
37 } else if (strcmp(argv[arg], "-h") == 0 || strcmp(argv[arg], "--help") == 0) {
38 printf("Usage: %s [options ...] [name ...]\n", argv[0]);
39 printf("Output each [name] with its last non-slash component and trailing slashes removed.\n"
40 "If [name] contains no /'s, then output is '.' (meaning the current directory)."
41 "\n"
42 " -z, --zero Separate output with NUL rather than newline.\n"
43 "\n"
44 " -h, --help Print this message.\n"
45 " -v, --version Show version info.\n");
46 return 0;
47 } else if (strcmp(argv[arg], "-v") == 0 || strcmp(argv[arg], "--version") == 0) {
48 printf("dirname (mutos) v"VERSION"\n");
49 return 0;
50 } else {
51 // no more flags
52 break;
56 for ( ; arg < argc; arg++)
58 int last_slash = -1;
59 for (size_t i = 0; i < strlen(argv[arg]); i++)
61 if (argv[arg][i] == '/' && i != strlen(argv[arg]) - 1) {
62 last_slash = i;
65 if (last_slash == -1) {
66 argv[arg] = ".";
67 } else {
68 argv[arg][last_slash] = '\0';
70 printf("%s%c", argv[arg], sep);