diff options
Diffstat (limited to 'binsub.c')
-rw-r--r-- | binsub.c | 50 |
1 files changed, 42 insertions, 8 deletions
@@ -1,7 +1,7 @@ /** - * binsub.c / 2022-12-09 + * binsub.c / 2025-02-23 * - * (C) 2022 Zach van Rijn <me@zv.io> + * (C) 2022-2025 Zach van Rijn <me@zv.io> * * MIT License * @@ -18,6 +18,8 @@ #include <stdio.h> #include <string.h> #include <stdlib.h> +#include <sys/types.h> +#include <sys/stat.h> /** * Basic memory structure. @@ -145,17 +147,40 @@ scanner (const char *file, const char *find, const char *repl) FILE *fp = NULL; size_t nb = 0; + struct stat st; + mode_t pold, pnew; + struct buffer buf; memset(&buf, 0, sizeof(struct buffer)); - fp = fopen(file, "rb+"); + if (stat(file, &st) == -1) + { + fprintf(stderr, + "E: Could not stat FILE '%s' at all!\n", + file + ); + return; + } + + pold = st.st_mode; /* don't want to modify this */ + pnew = pold | S_IWUSR; /* could be read-only file */ + + if (chmod(file, pnew) == -1) + { + fprintf(stderr, + "E: Could not chmod FILE '%s' for writing!\n", + file + ); + } + + fp = fopen(file, "rb"); if (!fp) { fprintf(stderr, "E: Could not open FILE '%s' for reading!\n", file ); - return; + goto restore; } fseek(fp, 0, SEEK_END); @@ -175,7 +200,7 @@ scanner (const char *file, const char *find, const char *repl) buf.len, file ); - return; + goto restore; } buf.data[buf.len] = 0; /* extra byte needs to be nil */ @@ -191,7 +216,7 @@ scanner (const char *file, const char *find, const char *repl) buf.len, file ); - return; + goto restore; } fclose(fp); @@ -205,7 +230,7 @@ scanner (const char *file, const char *find, const char *repl) "E: Could not open FILE '%s' for writing!\n", file ); - return; + goto restore; } nb = fwrite(buf.data, 1, buf.len, fp); @@ -220,11 +245,20 @@ scanner (const char *file, const char *find, const char *repl) buf.len, file ); - return; + goto restore; } fclose(fp); free(buf.data); + +restore: + if (chmod(file, pold) == -1) + { + fprintf(stderr, + "E: Could not restore FILE '%s' permissions!\n", + file + ); + } } |