简体   繁体   中英

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

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?

Use NSFileManager:

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM