Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 701
I60R Avatar asked Jan 28 '23 12:01

I60R


2 Answers

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".

like image 144
turbulencetoo Avatar answered Feb 03 '23 14:02

turbulencetoo


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.
like image 22
smaftoul Avatar answered Feb 03 '23 14:02

smaftoul