raddevus
raddevus

Reputation: 9077

Why does Rust output escape backslashes on paths in windows? What is best way to remove the extra backslashes from output?

Background

Writing a program that watches a directory and subdirs and alerts user when file(s) in the path are created, updated, edited. Code is shared on github.

I'm new to Rust (about 1 week of experience).

Make Output Path Easy to Use

I want user to be able to easily copy the output path (see pic below) and copy / paste it for use.

When I run the program on Linux it works great with directory separators (/ - forward slash) and the user can easily copy the path and use it.

Problem : Windows Platform Uses Backslashes

The problem is that on Windows platform paths are separated by backslashes (which are also escape chars).

Double-Backslashes

When the program outputs the path on Windows it always shows double backslashes and the path isn't easily copy-able.

Here's a snapshot of the output:

double backslashes on win10

As an example I am using the following output:

println!("{:?}", Path::new("c:\\windows\\"));

The output is from the Path::new() method itself, but it always outputs the path string with the double backslashes.

Can you help me find a better way to format the output so that it has single backslashes like a normal path (which excludes the escape backslashes)?

EDIT

Someone mentioned trying raw string input so I tried the following:

println!("{:?}", Path::new(r"c:\windows\"));

However, the Path::new method still outputs double backslashes.

Upvotes: 3

Views: 3841

Answers (1)

Skgland
Skgland

Reputation: 991

The Problem is that you are using the Debug formatting to print the path, this causes characters that would need to be escaped in a string literal to be escaped in the output.

Instead you should use the normal Display formatting, though as Path does not directly implement Display you will need to call display on the path to display it.

println!("{}", Path::new("c:\\windows\\").display());

Note that Path::display is not loss-less in case the path contains non-unicode data.

Upvotes: 13

Related Questions