wc: Added wc
[mutos-utils.git] / ln.c
blob8c4d087d519c04720367b341b1fae0584412af7e
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 <errno.h>
16 #include <stdbool.h>
17 #include <stdio.h>
18 #include <string.h>
20 #include <getopt.h>
21 #include <unistd.h>
23 #define VERSION "0.01"
25 // option flags
26 struct {
27 bool symbolic;
28 } flags;
30 void usage(char* program)
32 printf("Usage: %s [options] [mode] [file ...]\n", program);
33 printf("Changes file permissions.\n"
34 "\n"
35 " -s, --symbolic Create a symbolic link.\n"
36 "\n"
37 " --help Print this message.\n"
38 " --version Show version info.\n");
41 int main(int argc, char* argv[])
43 char* linkname = NULL;
44 char* sourcename = NULL;
46 flags.symbolic = false;
47 static struct option long_options[] = {
48 {"symbolic", no_argument, NULL, 's'},
49 {"help", no_argument, NULL, 1},
50 {"version", no_argument, NULL, 2},
51 {NULL, 0, NULL, 0}
54 int c = 0;
55 while ((c = getopt_long(argc, argv, "s",
56 long_options, NULL)) != -1)
58 switch (c)
60 case 's':
61 flags.symbolic = true;
62 break;
63 case 1:
64 usage(argv[0]);
65 return 0;
66 case 2:
67 printf("ln (mutos) v"VERSION"\n");
68 return 0;
69 default:
70 fprintf(stderr,"Run '%s --help' for usage.\n",
71 argv[0]);
72 return 1;
77 if ((argc - optind) < 1) {
78 fprintf(stderr, "%s: missing operands\n"
79 "Run '%s --help' for usage.\n",
80 argv[0], argv[0]);
81 return 1;
82 } else if ((argc - optind) == 1) {
83 sourcename = argv[optind];
84 linkname = argv[optind];
85 for (size_t i = strlen(argv[optind]); i != 0; i--)
87 if (argv[optind][i] == '/') {
88 linkname = argv[optind] + i + 1;
89 break;
92 } else if ((argc - optind) == 2) {
93 sourcename = argv[optind];
94 linkname = argv[optind+1];
95 } else {
96 fprintf(stderr, "%s: extra operand: %s\n",
97 argv[0], argv[optind+2]);
98 return 1;
101 int rc = 0;
102 if (flags.symbolic) {
103 rc = symlink(sourcename, linkname);
104 } else {
105 rc = link(sourcename, linkname);
108 if (rc != 0) {
109 fprintf(stderr, "%s: %s: %s\n",
110 argv[0], strerror(errno), linkname);
111 return 1;
114 return 0;