如何确定某个路径上是否存在符号链接? [英] How can I tell if a symbolic link exists at a certain path?

查看:118
本文介绍了如何确定某个路径上是否存在符号链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个原始文件, /path/to/foo.txt ,以及指向它的符号链接, / other / path / to /foo.txt 。我删除了 /path/to/foo.txt ,但将符号链接保留在原位。 如何使用Cocoa API判断符号链接是否仍然存在?

I have an original file, /path/to/foo.txt, and a symbolic link to it, /other/path/to/foo.txt. I delete /path/to/foo.txt, but leave the symbolic link in-place. How can I tell that the symbolic link still exists using Cocoa APIs?

我发现了这一点通过使用标准/推荐的 FileManager.fileExists(atPath: ) 。对于不熟悉该API的任何人来说,这里的问题是它遍历符号链接。因此,当我这样做时:

I found this by using the standard/recommended FileManager.fileExists(atPath:). The problem here, for anyone unfamiliar with that API, is that it traverses symlinks. So, when I do this:

FileManager.default.fileExists(atPath: "/other/path/to/foo.txt")

它会返回 false ,因为它看到我给了它一个符号链接并解决了它,然后看到在解决的路径上没有文件。

it returns false, because it saw that I gave it a symlink and resolved it, and then saw that there is no file at the resolved path.

如文档所述:


如果文件位于 path 无法访问您的应用程序,可能是因为无法访问一个或多个父目录,因此此方法返回 false 。如果 path 中的最后一个元素指定了符号链接,则此方法将遍历该链接并返回 true false 基于链接目标位置文件的存在。

If the file at path is inaccessible to your app, perhaps because one or more parent directories are inaccessible, this method returns false. If the final element in path specifies a symbolic link, this method traverses the link and returns true or false based on the existence of the file at the link destination.

似乎没有作为 FileManager 中的替代方法。因此,我想知道是否可以调用Cocoa API来告知其中是否存在符号链接,或者是否必须使用C或Bash API。

There doesn't seem to be an alternative in FileManager. So, I'm wondering if I can call a Cocoa API to tell if a symlink exists there, or if I'll have to resort to C or Bash APIs.

推荐答案

这是一个更简单的方法:Fondation / FileManger / FileWrapper

Here's a simpler way: Fondation/FileManger/FileWrapper

let node = try FileWrapper(url: URL(fileURLWithPath: "/PATH/file.link"), options: .immediate)

node.isDirectory      >> false
node.isRegularFile    >> false
node.isSymbolicLink   >> true

这篇关于如何确定某个路径上是否存在符号链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆