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