Search code examples
rustfilesystemsseparatoros-agnostic

How to access the file path separator for the current platform?


Are there any available option to get platform specific file separator in Rust?

There can be different platform specific separators:

let separator = "\\" // Could be this.
let separator2 = "/" // Could be this.
let separator3 = "//" // Could be this.

I am looking like something following:

let env_independent_seperator = env::separator()

Then it may be the usage can be follows:

let folder = "C\\Folder\\Path";
let env_independent_separator = env::separator() // Looking something like this
let file_name = "File.txt";
let full_path = folder+ env_independent_separator + file_name;

Are there any File::separator() in Rust?


Solution

  • Instead of using custom operations with separator one should use Pathbuf or Path for this problem.

    In case of platform specific separator one should use std::path::MAIN_SEPARATOR.

    UPDATE: As of Rust version 1.68 There is also std::path::MAIN_SEPARATOR_STR, which has the separator as a const &str