diff options
author | Joseph Hunkeler <jhunkeler@gmail.com> | 2022-01-18 23:04:23 -0500 |
---|---|---|
committer | Joseph Hunkeler <jhunkeler@gmail.com> | 2022-01-18 23:04:23 -0500 |
commit | fa3606a495e4df0c6231e433d3dffa19b7471a60 (patch) | |
tree | b82e449f91e4f9002decd9b4a6c1e24db1ada910 /append.c | |
parent | 76063b6148ee7f0d274799c562f896c0a2efa2cb (diff) | |
download | weekly-fa3606a495e4df0c6231e433d3dffa19b7471a60.tar.gz |
Refactor project structure
Diffstat (limited to 'append.c')
-rw-r--r-- | append.c | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/append.c b/append.c new file mode 100644 index 0000000..61b6ef6 --- /dev/null +++ b/append.c @@ -0,0 +1,63 @@ +#include "weekly.h" + +int append_stdin(const char *filename) { + FILE *fp; + size_t bufsz; + char *buf; + + bufsz = BUFSIZ; + buf = malloc(bufsz); + if (!buf) { + return -1; + } + + fp = fopen(filename, "a"); + if (!fp) { + perror(filename); + free(buf); + return -1; + } + +#if HAVE_WINDOWS + while (fgets(buf, (int) bufsz, stdin) != NULL) { + fprintf(fp, "%s", buf); + } +#else + while (getline(&buf, &bufsz, stdin) >= 0) { + fprintf(fp, "%s", buf); + } +#endif + free(buf); + fclose(fp); + return 0; +} + +int append_contents(const char *dest, const char *src) { + char buf[BUFSIZ] = {0}; + FILE *fpi, *fpo; + + fpi = fopen(src, "rb+"); + if (!fpi) { + perror(src); + return -1; + } + + fpo = fopen(dest, "ab+"); + if (!fpo) { + perror(dest); + fclose(fpi); + return -1; + } + + // Append source file to destination file + while (fread(buf, sizeof(char), sizeof(buf), fpi) > 0) { + fwrite(buf, sizeof(char), strlen(buf), fpo); + } + buf[0] = '\n'; + fwrite(buf, sizeof(char), 1, fpo); + + fclose(fpo); + fclose(fpi); + return 0; +} + |