aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.c
diff options
context:
space:
mode:
authorRafael G. Martins <rafael@rafaelmartins.eng.br>2015-04-20 03:52:36 -0300
committerRafael G. Martins <rafael@rafaelmartins.eng.br>2015-04-20 03:52:36 -0300
commit6164860c73613cd20ed179e6d92f9fe45c97c0b2 (patch)
tree0c8165795dd32e64454a24a0f03ccfb61a018255 /src/main.c
parent3b1b1aa6522c7d705ffdf36a7acc6e4db78a50a5 (diff)
downloadblogc-6164860c73613cd20ed179e6d92f9fe45c97c0b2.tar.gz
blogc-6164860c73613cd20ed179e6d92f9fe45c97c0b2.tar.bz2
blogc-6164860c73613cd20ed179e6d92f9fe45c97c0b2.zip
create output directories recursively
Diffstat (limited to 'src/main.c')
-rw-r--r--src/main.c45
1 files changed, 45 insertions, 0 deletions
diff --git a/src/main.c b/src/main.c
index 9d3eb5c..7a7197a 100644
--- a/src/main.c
+++ b/src/main.c
@@ -10,6 +10,14 @@
#include <config.h>
#endif /* HAVE_CONFIG_H */
+#ifdef HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif /* HAVE_SYS_STAT_H */
+
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif /* HAVE_SYS_TYPES_H */
+
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
@@ -47,6 +55,42 @@ blogc_print_usage(void)
}
+static void
+blogc_mkdir_recursive(const char *filename)
+{
+#if defined(HAVE_SYS_STAT_H) && defined(HAVE_SYS_TYPES_H)
+ // honor umask if possible
+ mode_t m = umask(0);
+ umask(m);
+ mode_t mode = (S_IRWXU | S_IRWXG | S_IRWXO) & ~m;
+#endif
+ char *fname = b_strdup(filename);
+
+ for (char *tmp = fname; *tmp != '\0'; tmp++) {
+ if (*tmp == '/' || *tmp == '\\') {
+#if defined(HAVE_SYS_STAT_H) && defined(HAVE_SYS_TYPES_H)
+ char bkp = *tmp;
+ *tmp = '\0';
+ if ((strlen(fname) > 0) && (-1 == mkdir(fname, mode)) && (errno != EEXIST)) {
+ fprintf(stderr, "blogc: error: failed to create output "
+ "directory (%s): %s\n", fname, strerror(errno));
+ free(fname);
+ exit(2);
+ }
+ *tmp = bkp;
+#else
+ // FIXME: show this warning only if actually trying to create a directory.
+ fprintf(stderr, "blogc: warning: can't create output directories "
+ "for your platform. please create the directories yourself.\n");
+ goto cleanup;
+#endif
+ }
+ }
+cleanup:
+ free(fname);
+}
+
+
int
main(int argc, char **argv)
{
@@ -110,6 +154,7 @@ main(int argc, char **argv)
FILE *fp = stdout;
if (!write_to_stdout) {
+ blogc_mkdir_recursive(output);
fp = fopen(output, "w");
if (fp == NULL) {
fprintf(stderr, "blogc: error: failed to open output file (%s): %s\n",