commit 9771af0e6dd4501205fd737aa2203361dd0c2102
parent 5d8bca26b9f4c263a87161a4d5485b0fe4f8a804
Author: Paco Esteban <paco@e1e0.net>
Date: Tue, 16 Jun 2020 17:46:07 +0200
copy files better
The old way failed with binary files. I guess EOF is a valid char for
binary files ????
Using a loop with fread(3) and fwrite(3) (with an intermediate buffer)
works better.
Diffstat:
1 file changed, 14 insertions(+), 4 deletions(-)
diff --git a/helpers.c b/helpers.c
@@ -56,14 +56,24 @@ copy_file(const char *source_file, const char *dest_file, int force)
}
if ((src_mtime > dst_mtime) || force) {
- if ((src = fopen(source_file, "r")) == NULL)
+ if ((src = fopen(source_file, "rb")) == NULL)
return -1;
- if ((dst = fopen(dest_file, "w")) == NULL)
+ if ((dst = fopen(dest_file, "wb")) == NULL)
return -1;
printf("copying %s --> %s\n", source_file, dest_file);
- while ((ch = fgetc(src)) != EOF)
- fputc(ch, dst);
+ size_t rcnt, wcnt;
+ unsigned char buff[4096];
+ do {
+ rcnt = fread(buff, 1, sizeof(buff), src);
+ if (rcnt) {
+ wcnt = fwrite(buff, 1, rcnt, dst);
+ } else {
+ wcnt = 0;
+ }
+ } while ((rcnt > 0) && (rcnt == wcnt));
+ if (wcnt)
+ return -1;
fclose(src);
fclose(dst);