Last active
December 15, 2015 17:49
-
-
Save vodik/5298904 to your computer and use it in GitHub Desktop.
Small utility to write to many files at once.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _GNU_SOURCE | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <errno.h> | |
#include <err.h> | |
#include <glob.h> | |
static int write_to(const char *msg, const char *path) | |
{ | |
FILE *fp = fopen(path, "w"); | |
if (!fp) { | |
warn("failed to open %s", path); | |
return 1; | |
} | |
fputs(msg, fp); | |
fclose(fp); | |
return 0; | |
} | |
static __attribute__((noreturn)) void usage(FILE *out) | |
{ | |
fprintf(out, "usage: %s [data] [files ...]\n", program_invocation_short_name); | |
exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
const char *msg = argv[1]; | |
int rc = 0, i; | |
glob_t gl; | |
if (argc < 3) | |
usage(stderr); | |
if (glob(argv[2], 0, NULL, &gl) < 0) | |
err(EXIT_FAILURE, "failed to glob %s", argv[2]); | |
/* append additional globs */ | |
for (i = 3; i < argc; ++i) { | |
if (glob(argv[i], GLOB_APPEND, NULL, &gl) < 0) | |
err(EXIT_FAILURE, "failed to glob %s", argv[i]); | |
} | |
/* write to each globbed file */ | |
for (i = 0; i < (int)gl.gl_pathc; ++i) | |
rc |= write_to(msg, gl.gl_pathv[i]); | |
globfree(&gl); | |
return rc; | |
} | |
// vim: et:sts=4:sw=4:cino=(0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment