main.c (1843B)
1 /** 2 * catrm, prompt option to cat a file before removing it. 3 **/ 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include "fcat.h" 8 9 enum OPTS { 10 OPTS_NONE = 0x00, 11 OPTS_INTERACTIVE = 0x01 12 }; 13 14 15 int prompt(const char *fpath); 16 int cat(const char *fpath); 17 int rm(const char *fpath); 18 void usage(const char *name) 19 { 20 printf("usage: %s [OPTIONS] [FILE]..\n", name); 21 puts(""); 22 puts("prompt the option to remove and/or cat a file."); 23 puts(""); 24 puts("options:"); 25 puts("\t-ni non-interactive mode, cat each listed file and remove it."); 26 puts(""); 27 exit(EXIT_SUCCESS); 28 } 29 30 31 int main(int argc, char *argv[]) 32 { 33 int opts = OPTS_INTERACTIVE, i; 34 35 for (i = 1; i < argc; ++i) { 36 if (!argv[i] || argv[i][0] != '-') continue; 37 38 if (strcmp(argv[i], "-h") == 0) 39 usage(argv[0]); 40 else if (strcmp(argv[i], "-ni") == 0) 41 opts &= ~OPTS_INTERACTIVE; 42 else 43 printf("unrecognised arg: '%s'", argv[i]); 44 argv[i] = 0; 45 } 46 47 for (i = 1; i < argc; ++i) { 48 if (!(opts & OPTS_INTERACTIVE)) { 49 cat(argv[i]); 50 rm(argv[i]); 51 } else if (prompt(argv[i]) == 'y') { 52 rm(argv[i]); 53 } 54 } 55 56 return EXIT_SUCCESS; 57 } 58 59 int prompt(const char *fpath) 60 { 61 int ret = 0; 62 char input = 'c'; 63 64 while (ret == 0) { 65 printf("remove file '%s' ([y]es/[n]o/[c]at)? ", fpath); 66 input = fgetc(stdin); 67 68 switch (input) { 69 case 'y': ret = 'y'; break; 70 case 'n': ret = 'n'; break; 71 case 'c': ret = cat(fpath); break; 72 default: break; 73 } 74 75 while (fgetc(stdin) != '\n'); 76 } 77 78 return ret; 79 } 80 81 int cat(const char *fpath) 82 { 83 FILE *f = 0; 84 int ret = 0; 85 86 if (!(f = fopen(fpath, "r"))) { 87 perror("failed to open file"); 88 ret = -1; 89 } 90 if (fcat(f, stdout) < 0) { 91 perror("fcat failed"); 92 ret = -1; 93 } 94 fclose(f); 95 96 return ret; 97 } 98 99 int rm(const char *fpath) 100 { 101 int ret = 0; 102 103 if (remove(fpath) != 0) { 104 perror("remove failed"); 105 ret = -1; 106 } 107 108 return ret; 109 }