How to move files and folders to Trash programmatically on macOS?

那年仲夏 提交于 2019-12-23 17:17:40

问题


All I can find on this topic is mentions of FSMoveObjectToTrashSync function, which is now deprecated and no alternative is listed for it.

How to do it from C or Objective-C code?


回答1:


Use NSFileManager:

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

  • trashItemAtURL:resultingItemURL:error: Moves an item to the trash.



回答2:


In C, you can use AppleScript to move files to the trash. Here's a simple example:

#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;
}

A few notes:

  • Multi-line scripts have to be sent as multiple -e command line options.
  • Since osascript insists on printing status messages to the command line console, I've redirected its output to /dev/null. But, if a file of the same name already exists in the trash, then the deleted file will be renamed. If you need to know this name, you'll have to use popen() instead of system() and parse the return string from osascript.


来源:https://stackoverflow.com/questions/51484900/how-to-move-files-and-folders-to-trash-programmatically-on-macos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!