*
*/
+#include <errno.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/stat.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)
}
+/* 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;
+}
+