X-Git-Url: https://git.donarmstrong.com/?a=blobdiff_plain;f=src%2Fcommon.c;h=9a11aecf47bf1cb59331da7a8da42a02242b3f5f;hb=a7a328a691ab370ed7fd61c9c04af9def02395d5;hp=b3f47edc166e5a2027cd6f3cb34cc2e04e2830d9;hpb=e25e049490086a631d12bc56785f1a1845877541;p=fastq-tools.git diff --git a/src/common.c b/src/common.c index b3f47ed..9a11aec 100644 --- a/src/common.c +++ b/src/common.c @@ -6,10 +6,16 @@ * */ +#include +#include +#include #include "common.h" #include "version.h" -#include + +#ifndef O_BINARY +#define O_BINARY 0 +#endif void print_version(FILE *f, const char* prog_name) @@ -61,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; +} +