You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:30:46