From: Fredrik Tolf Date: Sun, 5 Jun 2011 04:34:00 +0000 (+0200) Subject: Added nextep database program. X-Git-Url: http://git.dolda2000.com/gitweb/?a=commitdiff_plain;h=b2fa28e3cc2ebdf6f144716f5764fe6c87ca8a2f;p=utils.git Added nextep database program. --- diff --git a/nextep.c b/nextep.c new file mode 100644 index 0000000..a7bc746 --- /dev/null +++ b/nextep.c @@ -0,0 +1,96 @@ +#include +#include +#include +#include +#include +#include +#include + +static void usage(FILE *out) +{ + fprintf(out, "usage: nextep [-h] [-f FILE] [-s SET-VALUE] [DIR]\n"); +} + +int main(int argc, char **argv) +{ + int c; + char buf[1024], dbuf[1024], *p; + char *file, *value, *dir; + char base[1024], fpath[1024]; + FILE *fp; + + file = "nextep"; + value = NULL; + while((c = getopt(argc, argv, "hf:s:")) >= 0) { + switch(c) { + case 'f': + file = optarg; + break; + case 's': + value = optarg; + break; + case 'h': + usage(stdout); + exit(0); + default: + usage(stderr); + exit(1); + } + } + if(optind < argc) { + if(chdir(argv[optind])) { + fprintf(stderr, "nextep: %s: %s\n", argv[optind], strerror(errno)); + exit(1); + } + optind++; + } + if(!getcwd(dbuf, sizeof(dbuf))) { + fprintf(stderr, "nextep: getcwd: %s\n", strerror(errno)); + exit(1); + } + dir = basename(dbuf); + if((p = getenv("HOME")) == NULL) { + fprintf(stderr, "nextep: $HOME is not set\n"); + exit(1); + } + snprintf(buf, sizeof(buf), "%s/.nextep", p); + snprintf(base, sizeof(base), "%s/%s", buf, dir); + if(access(base, X_OK)) { + if((mkdir(buf, 0777) && (errno != EEXIST)) || mkdir(base, 0777)) { + fprintf(stderr, "nextep: %s: %s\n", base, strerror(errno)); + exit(1); + } + } + snprintf(fpath, sizeof(fpath), "%s/%s", base, file); + if(value == NULL) { + if((fp = fopen(fpath, "r")) == NULL) { + if(errno != ENOENT) { + fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno)); + exit(1); + } + } else { + while(fgets(buf, sizeof(buf), fp) != NULL) + printf(buf); + fclose(fp); + } + } else if(!*value) { + if(unlink(fpath) && (errno != ENOENT)) { + fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno)); + exit(1); + } + } else { + if((fp = fopen(fpath, "w")) == NULL) { + fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno)); + exit(1); + } + fprintf(fp, "%s\n", value); + fclose(fp); + } + return(0); +} + +/* + * Local Variables: + * compile-command: "gcc -Wall -g -o nextep nextep.c" + * End: + */