catrm

'cat' a file, then optionally 'rm' it. I just felt like writing C.
Log | Files | Refs | Atom | README

commit cb6d136f3fdba670a1c2abd3cb28f1c4da812164
parent 86be7e47644d3b49662200c3852d876bb50f9f09
Author: gearsix <gearsix@tuta.io>
Date:   Tue,  8 Mar 2022 16:16:24 +0000

finished main.c; fixed bugs & tidied

Diffstat:
Mmain.c | 72+++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
1 file changed, 49 insertions(+), 23 deletions(-)

diff --git a/main.c b/main.c @@ -1,5 +1,5 @@ /** - * + * catrm, prompt option to cat a file before removing it. **/ #include <stdio.h> #include <stdlib.h> @@ -12,7 +12,9 @@ enum OPTS { }; -int prompt(const char *fpath, const int opts); +int prompt(const char *fpath); +int cat(const char *fpath); +int rm(const char *fpath); int main(int argc, char *argv[]) @@ -20,51 +22,75 @@ int main(int argc, char *argv[]) int opts = OPTS_INTERACTIVE, i; for (i = 1; i < argc; ++i) { - if (!argv[argc] || argv[argc][0] != '-') continue; + if (!argv[i] || argv[i][0] != '-') continue; - if (strcmp(argv[argc], "-ni") == 0) - opts |= OPTS_INTERACTIVE; + if (strcmp(argv[i], "-ni") == 0) + opts &= ~OPTS_INTERACTIVE; else - printf("unrecognised arg: '%s'", argv[argc]); - argv[argc] = 0; + printf("unrecognised arg: '%s'", argv[i]); + argv[i] = 0; } for (i = 1; i < argc; ++i) { - if (prompt(argv[i], opts) == 'y') { - if (remove(argv[argc]) != 0) - perror("remove failed"); + if (!(opts & OPTS_INTERACTIVE)) { + cat(argv[i]); + rm(argv[i]); + } else if (prompt(argv[i]) == 'y') { + rm(argv[i]); } } return EXIT_SUCCESS; } -int prompt(const char *fpath, const int opts) +int prompt(const char *fpath) { int ret = 0; - char input; - FILE *f; + char input = 'c'; while (ret == 0) { printf("remove file '%s' ([y]es/[n]o/[c]at)? ", fpath); input = fgetc(stdin); + switch (input) { case 'y': ret = 'y'; break; case 'n': ret = 'n'; break; - case 'c': - if ((f = fopen(fpath, "r")) == NULL) { - perror("failed to open file"); - ret = 1; - } - if (fcat(f, stdout) < 0) - perror("cat failed"); - fclose(f); - break; + case 'c': ret = cat(fpath); break; default: break; } - + while (fgetc(stdin) != '\n'); } return ret; } + +int cat(const char *fpath) +{ + FILE *f = 0; + int ret = 0; + + if (!(f = fopen(fpath, "r"))) { + perror("failed to open file"); + ret = -1; + } + if (fcat(f, stdout) < 0) { + perror("fcat failed"); + ret = -1; + } + fclose(f); + + return ret; +} + +int rm(const char *fpath) +{ + int ret = 0; + + if (remove(fpath) != 0) { + perror("remove failed"); + ret = -1; + } + + return ret; +}