Search code examples
objective-cnsurlnsfilemanager

Check if directory is empty or remove only if empty in Objective-C


NSFileManager removeItemAtURL performs only recursive deletion. There is no special treatment for non-empty directories.

How can I remove only empty directories by testing the condition beforehand? There is contentsOfDirectoryAtPath to get a list of files, which may be empty, but that's overkill.

Alternately, is there a function to remove it only if empty, like good ol' rmdir? Ah, I could just call that…


Solution

  • You have to use that if you want to stay in Foundation land, there is no other way.

    But if you do so you introduce a race condition: After you list the contents of your directory and before you remove it some other program could write a new file there which then gets deleted. So you have to either accept the fact that you are deleting folders including all their content or you have to look for a different API.

    You could use the POSIX rmdir function to achieve your goal like this:

    NSString *path = [url path];
    int result = rmdir( [path fileSystemRepresentation] );
    if (result == 0) // everything ok
    else // lookup error code from errno
    

    If the directory is not empty you get the error code ENOTEMPTY.