Swift脚本首次运行无法写入文件,二次运行正常求解决方法
问题原因
你的代码里调用Process.run()执行touch命令是异步操作,调用后不会等待命令执行完成就立刻执行data.write(to:)。首次运行时,touch还没来得及创建文件,写入操作就触发了,导致失败;第二次运行时文件已经存在,所以写入成功。
解决方法
有两种可靠的修复方式:
方式1:等待touch命令执行完成
修改代码,在run()之后调用waitUntilExit(),确保touch创建完文件再执行写入:
func write_code_in_file(_ file_path: String,_ codes: String) { let write_code = Process() write_code.executableURL = URL(fileURLWithPath: "/usr/bin/env") write_code.arguments = ["touch", current_path+file_path] do { try write_code.run() write_code.waitUntilExit() // 新增:等待touch命令执行完毕 } catch { print("⚠️ Error - write code in file") } if let data: Data = codes.data(using: String.Encoding.utf8) { do { try data.write(to: URL(fileURLWithPath: current_path + file_path)) } catch let e { print("⚠️"+e.localizedDescription) } } }
方式2:用Swift原生API直接处理(更推荐)
完全不需要调用外部touch命令,Swift的FileManager和Data.write可以直接完成文件创建与写入,避免跨进程异步问题:
func write_code_in_file(_ file_path: String,_ codes: String) { let fileURL = URL(fileURLWithPath: current_path + file_path) if let data = codes.data(using: .utf8) { do { // 确保文件的父目录存在,防止因目录不存在写入失败 try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil) // 写入文件,文件不存在则自动创建,.atomic保证写入的原子性 try data.write(to: fileURL, options: [.atomic]) } catch let e { print("⚠️"+e.localizedDescription) } } }
内容的提问来源于stack exchange,提问作者Jihoonahn
相关产品推荐
相关产品推荐

