summaryrefslogtreecommitdiffstats
path: root/util.c
diff options
context:
space:
mode:
authorTavian Barnes <tavianator@tavianator.com>2021-09-21 18:47:28 -0400
committerTavian Barnes <tavianator@tavianator.com>2021-09-21 18:47:28 -0400
commit2e918d33be152c1a57ffb3ff53e344cafb161a8c (patch)
tree1549a3e1be09d4e565bfa58de0c03191e3d4e718 /util.c
parent10cb15e914bcf9257f14e09302fb4ab5b0aaf348 (diff)
downloadbfs-2e918d33be152c1a57ffb3ff53e344cafb161a8c.tar.xz
util: New xfopen() utility
And use it to pass O_CLOEXEC to all FILE*'s, so the files opened for -fprint etc. don't get passed to the programs run by -exec etc.
Diffstat (limited to 'util.c')
-rw-r--r--util.c45
1 files changed, 45 insertions, 0 deletions
diff --git a/util.c b/util.c
index d913b7d..728f962 100644
--- a/util.c
+++ b/util.c
@@ -16,6 +16,7 @@
#include "util.h"
#include "dstring.h"
+#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <langinfo.h>
@@ -426,3 +427,47 @@ char *xgetdelim(FILE *file, char delim) {
return NULL;
}
}
+
+FILE *xfopen(const char *path, int flags) {
+ char mode[4];
+
+ switch (flags & O_ACCMODE) {
+ case O_RDONLY:
+ strcpy(mode, "rb");
+ break;
+ case O_WRONLY:
+ strcpy(mode, "wb");
+ break;
+ case O_RDWR:
+ strcpy(mode, "r+b");
+ break;
+ default:
+ assert(!"Invalid access mode");
+ return NULL;
+ }
+
+ if (flags & O_APPEND) {
+ mode[0] = 'a';
+ }
+
+ int fd;
+ if (flags & O_CREAT) {
+ fd = open(path, flags, 0666);
+ } else {
+ fd = open(path, flags);
+ }
+
+ if (fd < 0) {
+ return NULL;
+ }
+
+ FILE *ret = fdopen(fd, mode);
+ if (!ret) {
+ int error = errno;
+ close(fd);
+ errno = error;
+ return NULL;
+ }
+
+ return ret;
+}