Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 605
Setjmp Avatar asked Mar 29 '11 03:03

Setjmp


People also ask

How do you remove a directory and all of its contents?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.

Which method is used to delete a directory?

Deleting file/dir using the os. rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.

Can rm remove a directory?

The rm command removes complete directories, including subdirectories and files. The rmdir command removes empty directories.


1 Answers

Use the nftw() (File Tree Walk) function, with the FTW_DEPTH flag. Provide a callback that just calls remove() on the passed file:

#define _XOPEN_SOURCE 500 #include <stdio.h> #include <ftw.h> #include <unistd.h>  int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {     int rv = remove(fpath);      if (rv)         perror(fpath);      return rv; }  int rmrf(char *path) {     return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS); } 
like image 197
caf Avatar answered Nov 15 '22 12:11

caf