swiftcocoasymlinknsfilemanagersymlink-traversal

How can I tell if a symbolic link exists at a certain path?


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?


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

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.

As the documentation says:

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.

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.


Solution

  • 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