Alex Rivera | Logout

How to delete a directory and its contents in (POSIX) C?

Asked 2011-03-29T03:56:57.420
29

I am most interested in the non-recursive case, but I am guessing others who might track this question would prefer seeing the recursive case.

Basically, we are aiming to accomplish:

rm -rf <target>

However, a system call would be an immature answer.

Edit
Report

1 Answer

3

See man 2 unlink and man 2 rmdir for system calls that will delete files and (empty) directories respectively. All you need to do then in order to handle the recursive case is to traverse the target directory in a post-order depth-first traversal and delete each entry in that order with the correct deletion routine. You can use opendir, readdir, and closedir to traverse the directory structure.

answered 2011-03-29T04:05:06.707

Your Answer