获取全路径或转换为全路径 [英] Get fullpath or convert to fullpath

查看:104
本文介绍了获取全路径或转换为全路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用时

let directoryEnumerator = FileManager().enumerator(at: ...

在Swift 3中,我从该文件夹中获取了所有文件,例如

in Swift 3, I get all files from the folder, e.g.

"file:///Volumes/MacOS/fasttemp/Fotos/"

结果不包括前导路径(此处为"/Volumes/MacOS").所以我得到

The results are not including the leading path (here "/Volumes/MacOS"). So I get

"file:///fasttemp/Fotos/2005/"

如何获取完整路径(直接从枚举器获取)或进行转换.我想使用URL函数,而不是通过假设操作的字符串函数.

How can I get the fullpath (directly from the enumerator) or convert them. I want to use URL functions, not string function manipulating by assumptions.

推荐答案

如果"MacOS"是当前启动磁盘的名称,则"/Volumes/MacOS"是"/"的符号链接,因此"/fasttemp" /Fotos/2005/"和"/Volumes/MacOS/fasttemp/Fotos/"是同一文件的绝对路径.

If "MacOS" is the name of your current startup disk then "/Volumes/MacOS" is a symbolic link to "/", so both "/fasttemp/Fotos/2005/" and "/Volumes/MacOS/fasttemp/Fotos/" are absolute paths to the same file.

为了获得唯一的文件名表示形式,您可以查询 规范路径的URL.示例:

In order to get a unique file name representation you can query a URL for its canonical path. Example:

let url = URL(fileURLWithPath: "/Volumes/MacOS/Applications/Utilities/")
if let cp = (try? url.resourceValues(forKeys: [.canonicalPathKey]))?.canonicalPath {
    print(cp)
}
// Output: "/Applications/Utilities"

这需要macOS 10.12/iOS 10或更高版本.在较旧的系统上,您可以 使用realpath()系统调用:

This requires macOS 10.12/iOS 10 or later. On older systems you can use the realpath() system call:

if let rp = url.withUnsafeFileSystemRepresentation ({ realpath($0, nil) }) {
    let fullUrl = URL(fileURLWithFileSystemRepresentation: rp, isDirectory: true, relativeTo: nil)
    free(rp)
    print(fullUrl.path)
}
// Output: "/Applications/Utilities"

这篇关于获取全路径或转换为全路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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