What happens when unlink a directory?

stonestrong picture stonestrong · Mar 11, 2013 · Viewed 12.1k times · Source

Suppose c.txt is in directory b. unlink c.txt is easy, the system just removes entry {XXX, c.txt} in directory b. But what happens if b is a subdirectory of a, and I want to unlink b, is the procedure the same or more complicated?

Answer

mvp picture mvp · Mar 11, 2013

unlink(2) can only delete a file, while rmdir(2) can only delete empty directory.

If you want to delete directory recursively, you must use both syscalls intelligently. You may find many different implementations of recursive delete, for example this one is using nftw, or this one is using opendir/readdir.