Quite simply, I want to delete a file that may or may not exist. Is it bad practice to just use remove(filename) and ignore the return value?
EDIT: By remove, I'm referring to this
Quite simply, I want to delete a file that may or may not exist. Is it bad practice to just use remove(filename) and ignore the return value?
EDIT: By remove, I'm referring to this
Should I check whether a file exists before deleting it?
There is no such requirement or need, and doing so is in no way useful.
and ignore the return value?
Usually, the user may want to know whether a file was deleted or not, so it is often a bad idea to ignore the return value. Further, the user probably also wants to know why a file was not deleted (see std::perror
).
As soon as you can't just lock filesystem for
you cant guarantee that after 1
check file wasn't been removed by another process.
So you should:
remove
functionperror
call]The answer to your question really depends for your program, and the link you gave is very helpful. If your program was trivial, I wouldn't do it, but if your program was nontrivial, I would check the value, like cpluslplus.com did, because you always should check return values. It is bad not to, because it's like saying:"I won't check the return value to this function, and intentionally not cover all possibilities."
C++ Should I check whether a file exists before deleting it?
You can, but you should never rely on the result in your code. You could introduce a race condition between your code and other threads/applications that may be competing over the same file. Consider the following:
foo.txt
exists. Result is true.foo.txt
exists. Result is true.foo.txt
. Success!foo.txt
. Whoops!Is it bad practice to just use remove(filename)...
No, not at all.
...and ignore the return value?
The only time you want to ignore the return code of a system call is when you really don't care about the outcome, which is very rare indeed. When deleting the file, you should be recording the return value, and then if/when the file cannot be deleted (e.g. permission issues, already deleted etc) you can inform the user that the operation failed or log it for debugging purposes.
This is quite a difficult question to answer. If you don't care if the file is actually deleted or not, but all means, ignore the return value. Without checking the return value, you cannot guarantee if the file has been deleted. Most likely, it will have been, but what if it's locked for some reason? Then you could be in trouble. As someone has pointed out, not checking the return code is very much a hit and hope scenario.