Skip to content

read_to_string_opt

Reads a whole file as text, giving None instead of an error when it does not exist.

Every other failure (permissions, a directory, invalid UTF-8) is still an error: only “not found” means “no value”.

use helpers4::fs::read_to_string_opt;

Cargo feature fs (enabled by default). To compile only this module:

cargo add helpers4 --no-default-features --features fs

or in Cargo.toml:

[dependencies]
helpers4 = { version = "0.0.6", default-features = false, features = ["fs"] }
pub fn read_to_string_opt(path: impl AsRef<Path>) -> io::Result<Option<String>>
ParameterTypeDescription
pathimpl AsRef<Path>The file to read.

io::Result<Option<String>>

Any io::Error from std::fs::read_to_string except io::ErrorKind::NotFound.

use helpers4::fs::read_to_string_opt;

assert_eq!(read_to_string_opt("/definitely/not/here.txt")?, None);

src/fs/read_to_string_opt.rs