dvd-sector-copy.c: Factor out some file-hacking machinery.
authorMark Wooding <mdw@distorted.org.uk>
Sat, 19 Feb 2022 01:58:34 +0000 (01:58 +0000)
committerMark Wooding <mdw@distorted.org.uk>
Sat, 19 Feb 2022 01:58:34 +0000 (01:58 +0000)
dvd-sector-copy.c

index 4e5f97b..418262f 100644 (file)
@@ -104,6 +104,32 @@ static void carefully_write(int fd, const void *buf, size_t sz)
   }
 }
 
+static void open_file_on_demand(const char *file, FILE **fp_inout,
+                               const char *what)
+{
+  FILE *fp;
+
+  if (!*fp_inout) {
+    fp = fopen(file, "w");
+    if (!fp)
+      bail_syserr(errno, "failed to open %s file `%s'", what, file);
+    fprintf(fp, "## %s\n\n", what);
+    *fp_inout = fp;
+  }
+}
+
+static void check_write(FILE *fp, const char *what)
+{
+  fflush(fp);
+  if (ferror(fp)) bail_syserr(errno, "error writing %s file", what);
+}
+
+static void carefully_fclose(FILE *fp, const char *what)
+{
+  if (fp && (ferror(fp) || fclose(fp)))
+    bail_syserr(errno, "error writing %s file", what);
+}
+
 #define DEFVEC(vtype, etype)                                           \
        typedef struct { etype *v; size_t n, sz; } vtype
 #define VEC_INIT { 0, 0, 0 }
@@ -477,17 +503,9 @@ static void recovered(secaddr bad_lo, secaddr bad_hi)
   moan("skipping %"PRIuSEC" bad sectors (%"PRIuSEC" .. %"PRIuSEC")",
        bad_hi - bad_lo, bad_lo, bad_hi);
   if (mapfile) {
-    if (!mapfp) {
-      mapfp = fopen(mapfile, "w");
-      if (!mapfp)
-       bail_syserr(errno, "failed to open bad-sector map file `%s'",
-                   optarg);
-      fprintf(mapfp, "## bad sector map\n\n");
-    }
+    open_file_on_demand(mapfile, &mapfp, "bad-sector region map");
     fprintf(mapfp, "%"PRIuSEC" %"PRIuSEC"\n", bad_lo, bad_hi);
-    fflush(mapfp);
-    if (ferror(mapfp))
-      bail_syserr(errno, "error writing bad-sector map file");
+    check_write(mapfp, "bad-sector region map");
   }
   if (lseek(outfd, (off_t)(bad_hi - bad_lo)*SECTORSZ, SEEK_CUR) < 0)
     bail_syserr(errno, "failed to seek past bad sectors");
@@ -1178,10 +1196,7 @@ int main(int argc, char *argv[])
   if (dvd) DVDClose(dvd);
   if (dvdfd >= 0) close(dvdfd);
   if (outfd >= 0) close(outfd);
-  if (mapfp) {
-    if (ferror(mapfp) || fclose(mapfp))
-      bail_syserr(errno, "error writing bad-sector map file");
-  }
+  carefully_fclose(mapfp, "bad-sector region map");
 
 #undef f_bogus
 #undef f_continue