0

Is it possible for a cocoa app to retrieve the size of the trash as an int. Is NSTask the correct method to do this?

Monolo
  • 18,205
  • 17
  • 69
  • 103

1 Answers1

3

There's no easy way to do this. Although the Mac GUI presents a unified Trash, there's not just one thing which is the trash. Each volume can have a separate trash and volumes can come and go.

Also, it can be quite time-consuming to calculate the size of the contents of a folder, so this doesn't seem like a very good idea.

If you really want to do it, you'd enumerate all of the mounted volumes using something like -[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:], convert the URLs to FSRefs using CFURLGetFSRef(), get a volume reference number from the FSRef using FSGetCatalogInfo() passing kFSCatInfoVolume for whichInfo, find the Trash for each volume using FSFindFolder() passing kTrashFolderType for folderType, convert the resulting FSRef to a URL using CFURLCreateFromFSRef(), create a directory enumerator for that URL using -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: passing NSURLTotalFileAllocatedSizeKey in the keys array, enumerate through that enumerator getting each item's NSURLTotalFileAllocatedSizeKey as an NSNumber, and accumulating the -unsignedLongLongValues of those NSNumbers.

It may actually be easier to enumerate the volumes using FSGetVolumeInfo(), passing kFSInvalidVolumeRefNum for volume and an index, starting at 1, for volumeIndex. You'd also pass kFSVolInfoNone for whichInfo. You'd increment the index and repeat until it returns nsvErr. The advantage is that this gives you the volume reference number directly so you don't have to go from URL to FSRef to volume reference number. The disadvantage is that this is one more old-style API. However, you have no choice but to use those APIs because there's no substitute for FSFindFolder() in the above.

Anyway, as you enumerate over the volumes get their trash folders, you have to be prepared to encounter volumes which don't have trash folders. For example, network-mounted volumes often don't.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154