【问题标题】:How to move files and folders to Trash programmatically on macOS?如何在 macOS 上以编程方式将文件和文件夹移动到垃圾箱?
【发布时间】:2018-12-31 06:23:18
【问题描述】:

关于这个话题我能找到的只是提到了FSMoveObjectToTrashSync 函数,现在是deprecated and no alternative is listed for it

如何从 C 或 Objective-C 代码中做到这一点?

【问题讨论】:

标签: objective-c c macos recycle-bin


【解决方案1】:

使用 NSFileManager:

https://developer.apple.com/documentation/foundation/nsfilemanager

  • trashItemAtURL:resultingItemURL:错误: 将项目移至回收站。

【讨论】:

    【解决方案2】:

    在 C 语言中,您可以使用 AppleScript 将文件移动到垃圾箱。这是一个简单的例子:

    #include <stdio.h>
    #include <stdlib.h>
    
    #define PATH "/tmp/"
    #define NAME "delete-me.txt"
    
    int main() {
        int status;
    
        /* Create a file */
        FILE *f;
        f = fopen(PATH NAME, "w");
        if (!f) {
            fputs("Can't create file " PATH NAME "\n", stderr);
            return 1;
        }
        fputs("I love trash\n", f);
        fclose(f);
    
        /* Now put it in the trash */
        status = system(
            "osascript -e 'set theFile to POSIX file \"" PATH NAME "\"' "
                      "-e 'tell application \"Finder\"' "
                          "-e 'delete theFile' "
                      "-e 'end tell' "
                      ">/dev/null"
        );
    
        if (status == 0) {
            puts("Look in the trash folder for a file called " NAME);
        }
        else {
            puts("Something went wrong. Unable to delete " PATH NAME);
        }
        return 0;
    }
    

    几点说明:

    • 多行脚本必须作为多个-e 命令行选项发送。
    • 由于osascript 坚持将状态消息打印到命令行控制台,我已将其输出重定向到/dev/null但是,如果垃圾箱中已经存在同名文件,则删除的文件将被重命名。如果您需要知道此名称,则必须使用 popen() 而不是 system() 并解析来自 osascript 的返回字符串。

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2017-06-11
      • 2019-11-28
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      相关资源
      最近更新 更多