25

How do you guys typically delete files on Linux OS? I am thinking of using the unlink function call, but I wonder if you have a better idea, as the C++ standard has no mention of file deletion operation and it is system dependent.

tshepang
  • 12,111
  • 21
  • 91
  • 136

5 Answers5

31

Yep -- the C++ standard leaves this stuff up to the OS, so if you're on Linux (or any POSIX system), unlink() is what you've got.

The C standard provides remove(), which you could try, but keep in mind that its behavior is unspecified for anything other than a 'regular file', so it doesn't really shield you from getting into platform-specific filesystem details (links, etc).

If you want something higher-level, more robust, and more portable, check out Boost Filesystem.

Todd Gamblin
  • 58,354
  • 15
  • 89
  • 96
20

The Standard includes a function called remove which does that. Though i would prefer boost.filesystem for that (if i already use boost anyway).

#include <cstdio>

int main() {
    std::remove("/home/js/file.txt");
}
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
2

unlink() is defined by the POSIX standards, and hence will exist on any POSIX compatible system, and on quite a few that aren't POSIX compatible too.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

unlink is the correct way to do it.

Lawrence D'Anna
  • 2,998
  • 2
  • 22
  • 25
0

Note that recent kernels also offer unlinkat. This function is faster than unlink if you have a file descriptor on the directory itself.

Yoric
  • 3,348
  • 3
  • 19
  • 26