To perform a recursive removal, you have to write a moderately complicated program which performs a file system walk. ISO C has no library features for this; it requires platform-specific functions for scanning the directory structure recursively.
On POSIX systems you can use opendir
, readdir
and closedir
to walk individual directories, and use programming language recursion to handle subdirectories. The functions ftw
and its newer variant nwft
perform an encapsulated file system walk; you just supply a callback function to process the visited paths. nftw
is better because it has a flags
argument using which you can specify the FTW_DEPTH
flag to do the search depth first: visit the contents of a directory before reporting the directory. That, of course, is what you want for recursive deletion.
On MS Windows, there is FindFirstFile
and FindNextFile
to cob together a recursive traversal.
About -f
, that only suppresses certain checks done by the rm
program above and beyond what the operating system requires. Without -f
, you get prompted if you want to delete a read-only file, but actually, in a Unix-like system, only the directory write permission is relevant, not that of the file, for deletion. The remove
library function doesn't have such a check.
By the way, remove
is in ISO C, so it is platform-independent. On POSIX systems, it calls rmdir
for directories and unlink
for other objects. So remove
is not only portable, but lets you not worry about what type of thing you're deleting. If a directory is being removed, it has to be empty though. (Not a requirement of the remove
function itself, but of mainstream operating systems that support it).