Quellcode durchsuchen

Use stat instead of open to check for existing files

Getty Ritter vor 5 Jahren
Ursprung
Commit
419e315ab2
1 geänderte Dateien mit 14 neuen und 12 gelöschten Zeilen
  1. 14 12
      src/lib.rs

+ 14 - 12
src/lib.rs

@@ -1,6 +1,7 @@
 use std::fmt::{self, Display, Formatter};
-use std::fs::OpenOptions;
+use std::fs::{self, OpenOptions};
 use std::io::{self, Write};
+use std::path::Path;
 
 const MAX_OUTPUT_FILES: u32 = 500;
 
@@ -67,24 +68,25 @@ impl SVG {
 
     /// Print this SVG document to stdout
     pub fn output(self, p: &str) -> io::Result<()> {
+        let output_dir = Path::new("output");
+        if !output_dir.is_dir() {
+            fs::create_dir(output_dir)?;
+        }
+
         let mut file = {
             let mut n = 0;
             let mut path = format!("output/{}{:05}.svg", p, n);
-            let mut f = OpenOptions::new().write(true).create_new(true).open(&path);
-            loop {
-                match f {
-                    Ok(_) => break,
-                    Err(ref e) if e.kind() != io::ErrorKind::AlreadyExists =>
-                        return Err(io::Error::new(e.kind(), "failed to create file")),
-                    _ if n > MAX_OUTPUT_FILES =>
-                        return Err(io::Error::new(io::ErrorKind::Other, "Too many output files already")),
-                    _ => (),
+            while Path::new(&path).exists() {
+                if n > MAX_OUTPUT_FILES {
+                    return Err(io::Error::new(
+                        io::ErrorKind::Other,
+                        "gunpowder_treason: too many output files",
+                    ));
                 }
                 n += 1;
                 path = format!("output/{}{:05}.svg", p, n);
-                f = OpenOptions::new().write(true).create_new(true).open(&path);
             }
-            f.unwrap()
+            OpenOptions::new().write(true).create_new(true).open(&path)?
         };
         self.write_svg(&mut file)
     }