使用swift的临时文件路径

编程入门 行业动态 更新时间:2024-10-11 11:15:19
本文介绍了使用swift的临时文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在OS X上使用Swift/Cocoa获得唯一的临时文件路径? 可可似乎没有为此提供功能,只有NSTemporaryDirectory()可以返回临时目录的路径.使用BSD mktemp函数需要一个可变的C字符串作为参数.

How to get a unique temporary file path using Swift/Cocoa on OS X? Cocoa does not seem to provide a function for this, only NSTemporaryDirectory() which returns the path of the temporary directory. Using the BSD mktemp function requires a mutable C-string as argument.

推荐答案

以下是使用 Swift 3 及更高版本中的mkstemp()的一种可能方法. URL方法 用于在URL实例和代表文件系统路径的C字符串之间进行转换:

Here is a possible method to use mkstemp() from Swift 3 and later. URL methods are used to convert between URL instances and C strings representing the file system path:

// The template string: let template = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("file.XXXXXX") as NSURL // Fill buffer with a C string representing the local file system path. var buffer = [Int8](repeating: 0, count: Int(PATH_MAX)) template.getFileSystemRepresentation(&buffer, maxLength: buffer.count) // Create unique file name (and open file): let fd = mkstemp(&buffer) if fd != -1 { // Create URL from file system string: let url = URL(fileURLWithFileSystemRepresentation: buffer, isDirectory: false, relativeTo: nil) print(url.path) } else { print("Error: " + String(cString: strerror(errno))) }

Swift 2的旧代码

// The template string: let template = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("file.XXXXXX") // Fill buffer with a C string representing the local file system path. var buffer = [Int8](count: Int(PATH_MAX), repeatedValue: 0) template.getFileSystemRepresentation(&buffer, maxLength: buffer.count) // Create unique file name (and open file): let fd = mkstemp(&buffer) if fd != -1 { // Create URL from file system string: let url = NSURL(fileURLWithFileSystemRepresentation: buffer, isDirectory: false, relativeToURL: nil) print(url.path!) } else { print("Error: " + String(strerror(errno))) }

更多推荐

使用swift的临时文件路径

本文发布于:2023-07-06 07:43:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   临时文件   swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!