]> 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 4598819ba2c9c126f27776095aafc4a9abdb8f64..9a11aecf47bf1cb59331da7a8da42a02242b3f5f 100644 (file)
@@ -6,9 +6,23 @@
  *
  */
 
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
 
 #include "common.h"
-#include <stdlib.h>
+#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;
+}
+