Search code examples
rustpathio

What is the best way to write a File given a Path instance?


If you have an instance of std::path::Path and want to write a text File to that path, what is the best way? I can call .display() to get a string and then use File I/O methods that take strings as file names, but is there a preferred way that involves something related to Path, PathBuf, etc? The .display() method is said to be lossy due to encoding issues so I would prefer a means that did not sacrifice generality.


Solution

  • You can use std::fs::write. The function has following signature, so it will work with Path objects too.

    pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()>