I60R
I60R

Reputation: 487

How to check if a symlink, not the file it points to, exists in Rust?

Path::exists is not suitable, since its documentation states:

This function will traverse symbolic links to query information about the destination file. In case of broken symbolic links this will return false.

Upvotes: 6

Views: 2914

Answers (2)

smaftoul
smaftoul

Reputation: 2713

std::fs::read_link seems what you want.

This function will return an error in the following situations, but is not limited to just these cases:

  • path is not a symbolic link.
  • path does not exist.

Upvotes: 3

turbulencetoo
turbulencetoo

Reputation: 3691

Another option is to use std::fs::symlink_metadata (docs).

Query the metadata about a file without following symlinks. This function will return an error ... [when] path does not exist.

The upside of this is that the returned Metadata struct contains a FileType struct (docs), which you can query about whether the path is a plain file, a directory or a symbolic link. This could be useful if the possible outcomes were more than "link exists" and "link does not exist".

Upvotes: 5

Related Questions