seq: Return 1 when too few/many arguments are provided
[mutos-utils.git] / seq.c
blobe49e1b78a22330e0da919eed2a835e51a6d51723
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>
17 #include <stdlib.h> // atoi()
18 #include <stdbool.h>
20 #define VERSION "0.01"
22 struct {
23 bool w;
24 } flags;
26 char* sep = "\n";
27 char* term = NULL;
29 void seq(char* first, char* increment, char* last)
31 unsigned int width = 0;
33 if (flags.w) {
34 width = strlen(last);
37 for (int i = atoi(first); i <= atoi(last); i+=atoi(increment))
39 printf("%0*d%s", width, i, sep);
42 if (term) {
43 printf("%s", term);
47 int main(int argc, char* argv[])
49 flags.w = false;
51 if (argc == 1) {
52 fprintf(stderr, "%s: missing operand\n"
53 "Run '%s --help' for usage.\n",
54 argv[0], argv[0]);
55 return 1;
59 // flag parsing
60 int i = 0;
61 for (i = 1; i < argc; i++)
63 if (strcmp(argv[i], "-s") == 0) {
64 sep = argv[i + 1];
65 i++; // don't parse separator as a flag
66 } else if (strcmp(argv[i], "-t") == 0) {
67 term = argv[i + 1];
68 i++; // don't parse terminator as a flag
69 } else if (strcmp(argv[i], "-w") == 0 || strcmp(argv[i], "--equal-width") == 0) {
70 flags.w = true;
71 } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
72 printf("Usage: %s FIRST LAST\n", argv[0]);
73 return 0;
74 } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
75 printf("seq (mutos) v"VERSION"\n");
76 return 0;
77 } else {
78 break;
82 int args_left = argc - i;
84 switch (args_left)
86 case 0:
87 fprintf(stderr, "%s: too few arguments\n",
88 argv[0]);
89 return 1;
90 case 1:
91 seq("1", "1", argv[i]);
92 break;
93 case 2:
94 seq(argv[i], "1", argv[i+1]);
95 break;
96 case 3:
97 seq(argv[i], argv[i+1], argv[i+2]);
98 break;
99 default:
100 fprintf(stderr, "%s: too many arguments\n",
101 argv[0]);
102 return 1;
105 return 0;