1

How to remove a directory and all its content from a C program on a Linux machine? I managed to create a directory with mkdir("path", 0700); and now I wonder if there is a similar way to remove it and all its subfolders and files.

Jens
  • 69,818
  • 15
  • 125
  • 179
cabbasisi
  • 11
  • 1
  • 1
    In POSIX, there isn't a way to remove a subdirectory and all its contents — no. There is a way to remove an empty subdirectory (the inverse of create an empty subdirectory) — yes: it is [`rmdir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/rmdir.html). To remove contents too, investigate [`nftw()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nftw.html). There might be a Linux-specific function, too. Or you can run `rm -fr /the/directory` via `system()` or equivalent. – Jonathan Leffler Mar 27 '17 at 15:37
  • *"and all its subfolders and files"* -- You have to recursively delete its contents if it is not empty. I don't believe the C standard library has a built-in way to perform a recursive delete. – cdhowie Mar 27 '17 at 15:37
  • 1
    Probably the easiest way is by calling `rm -r` with `system()` or `fork/exec`. – Barmar Mar 27 '17 at 15:38
  • @Barmar Easiest? Probably. But I'd be hesitant to use this approach in anything but a simple toy/demo program. – cdhowie Mar 27 '17 at 15:40
  • Thank you all for your quick answers: the solution pointed out by @Barmar actually works. – cabbasisi Mar 27 '17 at 15:42
  • @cdhowie why should I avoid this approach? – cabbasisi Mar 27 '17 at 15:42
  • @cabbasisi: Because if you aren't careful, `rm -fr /home/user/Docs & Photos` to remove the `Docs & Photos` directory (singular — name with spaces and shell metacharacters) doesn't do what you expect. – Jonathan Leffler Mar 27 '17 at 15:45
  • @JonathanLeffler True, that's why I mentioned fork/exec, it avoids shell parsing issues. – Barmar Mar 27 '17 at 16:06
  • @cabbasisi It seems silly to depend on an external tool for something that is fairly trivially implemented in C. – cdhowie Mar 27 '17 at 18:05

0 Answers0