Global path of the currently open file in xcode 8 project in Swift 3.0

I need to get the global path of the currently open file in xcode 8 using Swift 3.0.

I cannot find such options in Foundation/Bundle and FileManager.

Replies

What do you mean by "the currently open file", are you referring to an NSDocument or similar?


For the more general question on how to get the path of an open file, given the filehandle, the following code fetches that information, but it is in C, and I could not find an easy way to call it in Swift, but it is trivial to make a wrapper in Objective-C that returns an NSString:


int ret;
struct vnode_fdinfowithpath vnode_info;
ret = proc_pidfdinfo(getpid(), fd, PROC_PIDFDVNODEPATHINFO, &vnode_info, sizeof(vnode_info));
if (ret < sizeof(vnode_info)) {
    fprintf(stderr, "failed\n");
    return;
}
vnode_info.pvip.vip_path[sizeof(vnode_info.pvip.vip_path) - 1] = '\0';
fprintf(stderr, "%s\n", vnode_info.pvip.vip_path);

For the more general question on how to get the path of an open file, given the filehandle, the following code fetches that information …

That code will work but it relies on libproc which is not public API on iOS-based platforms. A better option is

fcntl
with the
F_GETPATH
selector. For example:
import Darwin

func path(for descriptor: Int32) -> String? {
    var path = [CChar](repeating: 0, count: Int(MAXPATHLEN))
    let err = fcntl(descriptor, F_GETPATH, &path)
    guard err == 0 else {
        return nil
    }
    return String(validatingUTF8: path)
}

print(path(for: STDIN_FILENO))
// prints `Optional("/dev/ttys002")` when run from Xcode

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"