sajal
sajal

Reputation: 69

Forcefully deleting a file using c++ in linux

I have a code in c++ running on linux server. In the code, I am using function unlink(filename) to delete a file. Temporary files getting generated by the code itself are getting deleted successfully. But the files that I am putting manually, my code is unable to delete them. What could be the reason?

Upvotes: 1

Views: 1731

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129344

The way that for example rm -f works is that, if the file has protection that doesn't allow it to be deleted, it attempts to change the file protection and ownership, using the chmod() and chown() functions to "make it possible to delete the file". This is only really GUARANTEED to work if the user is root or the files actually belong to the user that runs the program.

Note that this becomes system dependent, you can't write code that changes file privileges etc in a way that works on both Windows and Unix-like OS's, and if you wanted to do this on, say, Symbian OS, it would be a third variant on how to do it Although there may be a "Posix compatible" chmod() available in some cases.

Upvotes: 1

hyde
hyde

Reputation: 62787

Try this:

#include <errno.h>
#include <string.h>

...

if (unlink(filename) == -1) {
    fprintf(stderr, "File '%s' unlink error (%d): %s\n", filename, errno, strerror(errno));
    // or just use perror("unlink") for less customizable error message
    // note: calling other functions before printing may change errno value
}

Resulting error message should reveal what the problem is.

Here's errno man page, and unlink man page will tell what errors it can return.


Hmm, since this is actually a C++ question, you could and possibly should replace fprintf with std::cerr, but in that case it may be necessary to first do int errtmp = errno and use that, to avoid iostream messing it up before it gets examined.

Also you could write ::unlink(filename) if you want to be explicit that it is a symbol in the top level namespace, at least some people consider that good practice even when not necessary.

Upvotes: 9

Related Questions