问题
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 usepopen()
instead ofsystem()
and parse the return string fromosascript
.
来源:https://stackoverflow.com/questions/51484900/how-to-move-files-and-folders-to-trash-programmatically-on-macos