Use stat instead of open to check for existing files
Getty Ritter
6 years ago
1 | 1 | use std::fmt::{self, Display, Formatter}; |
2 |
use std::fs:: |
|
2 | use std::fs::{self, OpenOptions}; | |
3 | 3 | use std::io::{self, Write}; |
4 | use std::path::Path; | |
4 | 5 | |
5 | 6 | const MAX_OUTPUT_FILES: u32 = 500; |
6 | 7 | |
67 | 68 | |
68 | 69 | /// Print this SVG document to stdout |
69 | 70 | pub fn output(self, p: &str) -> io::Result<()> { |
71 | let output_dir = Path::new("output"); | |
72 | if !output_dir.is_dir() { | |
73 | fs::create_dir(output_dir)?; | |
74 | } | |
75 | ||
70 | 76 | let mut file = { |
71 | 77 | let mut n = 0; |
72 | 78 | let mut path = format!("output/{}{:05}.svg", p, n); |
73 | let mut f = OpenOptions::new().write(true).create_new(true).open(&path); | |
74 | loop { | |
75 | match f { | |
76 | Ok(_) => break, | |
77 | Err(ref e) if e.kind() != io::ErrorKind::AlreadyExists => | |
78 | return Err(io::Error::new(e.kind(), "failed to create file")), | |
79 | _ if n > MAX_OUTPUT_FILES => | |
80 | return Err(io::Error::new(io::ErrorKind::Other, "Too many output files already")), | |
81 |
|
|
79 | while Path::new(&path).exists() { | |
80 | if n > MAX_OUTPUT_FILES { | |
81 | return Err(io::Error::new( | |
82 | io::ErrorKind::Other, | |
83 | "gunpowder_treason: too many output files", | |
84 | )); | |
82 | 85 | } |
83 | 86 | n += 1; |
84 | 87 | path = format!("output/{}{:05}.svg", p, n); |
85 | f = OpenOptions::new().write(true).create_new(true).open(&path); | |
86 | 88 | } |
87 |
|
|
89 | OpenOptions::new().write(true).create_new(true).open(&path)? | |
88 | 90 | }; |
89 | 91 | self.write_svg(&mut file) |
90 | 92 | } |