简体   繁体   中英

Check if a file is a symlink in Rust 2018 on Windows

I'm writing a small utility for myself that needs to be able to check if a file is a symlink or not.

Using FileType::is_symlink on Windows always returns false (goes for both symlinks to directories, and regular files).

Using regular Rust 2018 edition, is there any way to check if a file is a symlink on Windows?

In my searching, I came across: FileTypeExt - however this requires that you use unstable Rust, as far as I can tell.

Using File::metadata() or fs::metadata() to get the file type will always return false for FileType::is_symlink() because the link has already been followed at that point. The docs note that:

The underlying Metadata struct needs to be retrieved with thefs::symlink_metadata function and not the fs::metadata function. The fs::metadata function follows symbolic links, so is_symlink would always return false for the target file.

use std::fs;

fn main() -> std::io::Result<()> {
    let metadata = fs::symlink_metadata("foo.txt")?;
    let file_type = metadata.file_type();

    let _ = file_type.is_symlink();
    Ok(())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM