]> git.donarmstrong.com Git - fastq-tools.git/blobdiff - src/common.c
Fix the weird output behavior of fastq-sample.
[fastq-tools.git] / src / common.c
index b3f47edc166e5a2027cd6f3cb34cc2e04e2830d9..9a11aecf47bf1cb59331da7a8da42a02242b3f5f 100644 (file)
@@ -6,10 +6,16 @@
  *
  */
 
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
 
 #include "common.h"
 #include "version.h"
-#include <stdlib.h>
+
+#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;
+}
+