| 1 | #include <stdlib.h> |
| 2 | #include <stdio.h> |
| 3 | #include <unistd.h> |
| 4 | #include <string.h> |
| 5 | #include <libgen.h> |
| 6 | #include <errno.h> |
| 7 | #include <sys/stat.h> |
| 8 | |
| 9 | static void usage(FILE *out) |
| 10 | { |
| 11 | fprintf(out, "usage: nextep [-h] [-f FILE] [-s SET-VALUE] [DIR]\n"); |
| 12 | } |
| 13 | |
| 14 | int main(int argc, char **argv) |
| 15 | { |
| 16 | int c; |
| 17 | char buf[1024], dbuf[1024], *p; |
| 18 | char *file, *value, *dir; |
| 19 | char base[1024], fpath[1024]; |
| 20 | FILE *fp; |
| 21 | |
| 22 | file = "nextep"; |
| 23 | value = NULL; |
| 24 | while((c = getopt(argc, argv, "hf:s:")) >= 0) { |
| 25 | switch(c) { |
| 26 | case 'f': |
| 27 | file = optarg; |
| 28 | break; |
| 29 | case 's': |
| 30 | value = optarg; |
| 31 | break; |
| 32 | case 'h': |
| 33 | usage(stdout); |
| 34 | exit(0); |
| 35 | default: |
| 36 | usage(stderr); |
| 37 | exit(1); |
| 38 | } |
| 39 | } |
| 40 | if(optind < argc) { |
| 41 | if(chdir(argv[optind])) { |
| 42 | fprintf(stderr, "nextep: %s: %s\n", argv[optind], strerror(errno)); |
| 43 | exit(1); |
| 44 | } |
| 45 | optind++; |
| 46 | } |
| 47 | if(!getcwd(dbuf, sizeof(dbuf))) { |
| 48 | fprintf(stderr, "nextep: getcwd: %s\n", strerror(errno)); |
| 49 | exit(1); |
| 50 | } |
| 51 | dir = basename(dbuf); |
| 52 | if((p = getenv("HOME")) == NULL) { |
| 53 | fprintf(stderr, "nextep: $HOME is not set\n"); |
| 54 | exit(1); |
| 55 | } |
| 56 | snprintf(buf, sizeof(buf), "%s/.nextep", p); |
| 57 | snprintf(base, sizeof(base), "%s/%s", buf, dir); |
| 58 | if(access(base, X_OK)) { |
| 59 | if((mkdir(buf, 0777) && (errno != EEXIST)) || mkdir(base, 0777)) { |
| 60 | fprintf(stderr, "nextep: %s: %s\n", base, strerror(errno)); |
| 61 | exit(1); |
| 62 | } |
| 63 | } |
| 64 | snprintf(fpath, sizeof(fpath), "%s/%s", base, file); |
| 65 | if(value == NULL) { |
| 66 | if((fp = fopen(fpath, "r")) == NULL) { |
| 67 | if(errno != ENOENT) { |
| 68 | fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno)); |
| 69 | exit(1); |
| 70 | } |
| 71 | } else { |
| 72 | while(fgets(buf, sizeof(buf), fp) != NULL) |
| 73 | printf(buf); |
| 74 | fclose(fp); |
| 75 | } |
| 76 | } else if(!*value) { |
| 77 | if(unlink(fpath) && (errno != ENOENT)) { |
| 78 | fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno)); |
| 79 | exit(1); |
| 80 | } |
| 81 | } else { |
| 82 | if((fp = fopen(fpath, "w")) == NULL) { |
| 83 | fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno)); |
| 84 | exit(1); |
| 85 | } |
| 86 | fprintf(fp, "%s\n", value); |
| 87 | fclose(fp); |
| 88 | } |
| 89 | return(0); |
| 90 | } |
| 91 | |
| 92 | /* |
| 93 | * Local Variables: |
| 94 | * compile-command: "gcc -Wall -g -o nextep nextep.c" |
| 95 | * End: |
| 96 | */ |