]> git.donarmstrong.com Git - fastq-tools.git/blob - src/common.c
Fix the weird output behavior of fastq-sample.
[fastq-tools.git] / src / common.c
1
2 /*
3  * This file is part of fastq-tools.
4  *
5  * Copyright (c) 2011 by Daniel C. Jones <dcjones@cs.washington.edu>
6  *
7  */
8
9 #include <errno.h>
10 #include <fcntl.h>
11 #include <stdlib.h>
12
13 #include "common.h"
14 #include "version.h"
15
16 #ifndef O_BINARY
17 #define O_BINARY 0
18 #endif
19
20
21 void print_version(FILE *f, const char* prog_name)
22 {
23     fprintf(f, "%s (fastq-tools) %s\n",
24             prog_name, FASTQ_TOOLS_VERSION);
25 }
26
27
28 void or_die(int b, const char* msg)
29 {
30     if (b == 0) {
31         fputs(msg, stderr);
32         exit(1);
33     }
34 }
35
36
37 void* malloc_or_die(size_t n)
38 {
39     void* p = malloc(n);
40     if (p == NULL) {
41         fprintf(stderr, "Can not allocate %zu bytes.\n", n);
42         exit(1);
43     }
44     return p;
45 }
46
47
48 void* realloc_or_die(void* ptr, size_t n)
49 {
50     void* p = realloc(ptr, n);
51     if (p == NULL) {
52         fprintf(stderr, "Can not allocate %zu bytes.\n", n);
53         exit(1);
54     }
55     return p;
56 }
57
58
59 FILE* fopen_or_die(const char* path, const char* mode)
60 {
61     FILE* f = fopen(path, mode);
62     if (f == NULL) {
63         fprintf(stderr, "Can not open file %s with mode %s.\n", path, mode);
64         exit(1);
65     }
66     return f;
67 }
68
69
70 /* Open a file for writing, creating it if it doesn't exist, and complaining if
71  * it does. */
72 FILE* open_without_clobber(const char* filename)
73 {
74     int fd = open(filename, O_WRONLY | O_CREAT | O_BINARY | O_EXCL,
75                   S_IRUSR | S_IWUSR);
76
77     if (fd == -1) {
78         if (errno == EEXIST) {
79             fprintf(stderr, "Refusing to overwrite %s.\n", filename);
80             exit(EXIT_FAILURE);
81         }
82         else {
83             fprintf(stderr, "Cannot open %s for writing.\n", filename);
84             exit(EXIT_FAILURE);
85         }
86     }
87
88     FILE* f = fdopen(fd, "wb");
89     if (f == NULL) {
90         fprintf(stderr, "Cannot open %s for writing.\n", filename);
91         exit(EXIT_FAILURE);
92     }
93
94     return f;
95 }
96
97