X-Git-Url: https://git.donarmstrong.com/?a=blobdiff_plain;f=src%2Fcommon.c;h=9a11aecf47bf1cb59331da7a8da42a02242b3f5f;hb=a7a328a691ab370ed7fd61c9c04af9def02395d5;hp=4598819ba2c9c126f27776095aafc4a9abdb8f64;hpb=40ab4c0cde1bfee1616777995998b0cbc5ffc741;p=fastq-tools.git diff --git a/src/common.c b/src/common.c index 4598819..9a11aec 100644 --- a/src/common.c +++ b/src/common.c @@ -6,9 +6,23 @@ * */ +#include +#include +#include #include "common.h" -#include +#include "version.h" + +#ifndef O_BINARY +#define O_BINARY 0 +#endif + + +void print_version(FILE *f, const char* prog_name) +{ + fprintf(f, "%s (fastq-tools) %s\n", + prog_name, FASTQ_TOOLS_VERSION); +} void or_die(int b, const char* msg) @@ -53,4 +67,31 @@ FILE* fopen_or_die(const char* path, const char* mode) } +/* Open a file for writing, creating it if it doesn't exist, and complaining if + * it does. */ +FILE* open_without_clobber(const char* filename) +{ + int fd = open(filename, O_WRONLY | O_CREAT | O_BINARY | O_EXCL, + S_IRUSR | S_IWUSR); + + if (fd == -1) { + if (errno == EEXIST) { + fprintf(stderr, "Refusing to overwrite %s.\n", filename); + exit(EXIT_FAILURE); + } + else { + fprintf(stderr, "Cannot open %s for writing.\n", filename); + exit(EXIT_FAILURE); + } + } + + FILE* f = fdopen(fd, "wb"); + if (f == NULL) { + fprintf(stderr, "Cannot open %s for writing.\n", filename); + exit(EXIT_FAILURE); + } + + return f; +} +