2010-05-17 51 views
4

我沒有看到FSPathMoveObjectToTrashSync()函數的任何選項沒有關注鏈接。如何將符號鏈接移動到垃圾箱?

這是我曾嘗試

創建一個鏈接和文件

[ 21:32:41 /tmp ] $ touch my_file 
[ 21:32:45 /tmp ] $ ln -s my_file my_link 
[ 21:32:52 /tmp ] $ la 
total 8 
drwxrwxrwt 12 root  wheel 408 17 Maj 21:32 . 
[email protected] 6 root  wheel 204 9 Sep 2009 .. 
-rw-r--r-- 1 neoneye wheel  0 17 Maj 21:32 my_file 
lrwxr-xr-x 1 neoneye wheel  7 17 Maj 21:32 my_link -> my_file 

移動鏈接到垃圾

OSStatus status = FSPathMoveObjectToTrashSync(
    "/tmp/my_link", 
    NULL, 
    kFSFileOperationDefaultOptions 
); 
NSLog(@"status: %i", (int)status); 

輸出是

status: 0 

然而該文件得到了重新移動而不是鏈接

[ 21:32:55 /tmp ] $ la 
total 8 
drwxrwxrwt 11 root  wheel 374 17 Maj 21:33 . 
[email protected] 6 root  wheel 204 9 Sep 2009 .. 
lrwxr-xr-x 1 neoneye wheel  7 17 Maj 21:32 my_link -> my_file 
[ 21:33:05 /tmp ] $ 

如何將符號鏈接移動到垃圾箱?


解決方案..感謝Rob納皮爾

NSString* path = @"/tmp/my_link"; 
OSStatus status = 0; 

FSRef ref; 
status = FSPathMakeRefWithOptions(
    (const UInt8 *)[path fileSystemRepresentation], 
    kFSPathMakeRefDoNotFollowLeafSymlink, 
    &ref, 
    NULL 
); 
NSAssert((status == 0), @"failed to make FSRef"); 

status = FSMoveObjectToTrashSync(
    &ref, 
    NULL, 
    kFSFileOperationDefaultOptions 
); 
NSLog(@"status: %i", (int)status); 

回答

5

使用FSPathMakeRefWithOptions()生成FSRef的鏈接。然後使用FSMoveObjectToTrashSync()刪除它。

3

另一種方式是通過發送a performFileOperation:source:destination:files:tag: messagethe NSWorkspaceRecycleOperation operationa recycleURLs:completionHandler: message告訴NSWorkspace「回收」它。

我不知道它們中的任何一個能在符號鏈接上運行得如何,但如果您不想處理FSRef s,則值得嘗試。

+0

介紹了在10.6。很棒的發現。會嘗試。 – neoneye 2010-05-18 07:15:02

+0

neoneye:只有後一種方法在10.6中引入。前一種方法從10.0開始一直存在,並且仍然受到支持。 – 2010-05-18 07:58:54

0

我的復古未來主義的方法

https://github.com/reklis/recycle

// 
// main.swift 
// recycle 
// 
// usage: recycle <files or directories to throw out> 
// 

import Foundation 
import AppKit 

var args = NSProcessInfo.processInfo().arguments 
args.removeAtIndex(0) // first item in list is the program itself 

var w = NSWorkspace.sharedWorkspace() 
var fm = NSFileManager.defaultManager() 

for arg in args { 
    let path = arg.stringByStandardizingPath; 

    let file = path.lastPathComponent 
    let source = path.stringByDeletingLastPathComponent 

    w.performFileOperation(NSWorkspaceRecycleOperation, 
     source:source, 
     destination: "", 
     files: [file], 
     tag: nil) 
} 
相關問題