1

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

This is in a standard Linux environment.

Thanks!

(I'm aware of rmdir but this isn't what I'm looking for.)

Community
  • 1
  • 1
Aaron Yodaiken
  • 19,163
  • 32
  • 103
  • 184

2 Answers2

2

You'll want to traverse the directory tree, using nftw for file tree walk. For the rm -r example, use the flag FTW_DEPTH to process contents first, and check for FTW_D to use rmdir on directories rather than remove or unlink. Of course this doesn't guarantee you're allowed to remove things; that's generally decided by write persmission of the containing directory.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
-1

What's wrong with system("rm -rf");?


update: since commenters are showing with their comments that it's easy to miss the point, let me expand to clarify:

if (chdir(dirName) != 0)
  return -1;
if (system("rm -rf .") != 0)
  return -2;
CAFxX
  • 28,060
  • 6
  • 41
  • 66
  • 1
    The fact that it's using `system`, and you'll probably introduce **extremely serious** vulns when you go tacking on a name to the end of that... – R.. GitHub STOP HELPING ICE Apr 17 '11 at 17:36
  • Consider when someone gives you a name like `{/,foo}` or `* ~` (the classical mistake of a space while trying to remove only backup copies). – Yann Vernier Apr 17 '11 at 17:42
  • @R that's outside the scope of the question isn't it? besides, your point could apply to any other method as long as you don't check the inputs. just `chdir()`ing to the directory you want to remove, checking that you unded up somewhere sane and then `system("rm -rf .");` should be safe... – CAFxX Apr 18 '11 at 07:01
  • Not to mention arguments like `foo ; mailx -s 'I resign' my-boss` (standard command injection) – Toby Speight Oct 03 '19 at 16:14
  • @TobySpeight read my comment immediately above yours. – CAFxX Oct 06 '19 at 05:03
  • I updated my answer to preempt further pointless comments. – CAFxX Oct 06 '19 at 05:11
  • You can't `rm -rf .`; it tries to remove the directory that it's being run from, which will always fail, and (in this example) will cause the calling function to return `-2`. – S.S. Anne Oct 06 '19 at 21:21
  • The update improves things; it may be wise to avoid depending on `PATH`, too (either unset the variable, or specify the absolute path to `rm`). – Toby Speight Oct 07 '19 at 08:38