当您使用 swift 以编程方式删除文件时,文件去了哪里?

Where do files go when you delete them programatically with swift?

当您以编程方式删除文件时,文件去了哪里?我用这段代码删除了它们,但今天的垃圾桶是空的。是否可以取回它们?

let filemgr = NSFileManager.defaultManager()
        do{
            let filelist = try filemgr.contentsOfDirectoryAtPath(fontFolderPath)
            for filename in filelist {
                do{ try filemgr.removeItemAtPath(fontFolderPath+filename)} catch{}
            }
        }catch{}

removeItemAtPath 方法删除它们。他们走了。如果你想把东西移到垃圾箱,你需要使用NSWorkSpace. You can see an example of moving an entire directory to the trash here: Move directory to trash

使用 NSFileManager 的 URL 相关 API 你有两个选择:

  • func removeItemAtURL(_ URL: NSURL) throws

    像 Terminal.app 中的 /bin/rm 一样立即删除项目,并且具有与 removeItemAtPath.

  • 相同的功能
  • func trashItemAtURL(_ url: NSURL, resultingItemURL outResultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throws

    将项目移动到回收站文件夹,通过 inout 指针返回项目在回收站中的位置。

基本上unixy系统管理文件的方式是一样的,有一个ref count,就是硬链接的数量+文件打开的次数...所以你可以rm一个打开的文件,文件仍然存在,您可以使用有效的 file descriptorFILE * 流对象对其进行写入和读取,然后当它关闭时,文件实际上将从磁盘中删除...

int fd = open("somefile", O_RDWR);
unlink("somefile"); // removes somefile from the directory listing, but not disk
write(fd, "hello", 5);
lseek(fd,0,SEEK_SET); // seek to start of file 
char buffer[6] = {0};
read(fd,buffer,5); // reads in "hello"
close(fd); // last reference removed, file is removed.

如果您想将文件移动到回收站,这是一个不同的操作,特定于 OS X 和 iOS