Re: can not delete a file
George wrote:
I am using the following program to delete all files in a specified
directory. But when running, no files could be deleted, and the related
error information is,
failed with error 5 -- access denied.
Where exactly does this occur? Also, I think (read the MSDN!) that
FindFirstFile/FindNextFile also find "." and ".."!
hFind = FindFirstFile(path, &FindFileData);
if (hFind == INVALID_HANDLE_VALUE)
{
FindClose(hFind);
return -1;
}
else
{
Some suggestions here:
1. 'int' is not the best of all return types. If you are using C++, I would
rather throw an exception, for C I would still return an errorcode (i.e.
the one from GetLastError()).
2. FindClose() is wrong here, as you only execute that code when
FindFirstFile() failed. IOW, there is nothing to close here!
3. I would not use an 'else' after a 'return'. That makes it easier to
divide the function in two parts that can be understood separately. This is
a matter of taste though.
// delete 1st file
rtn = DeleteFile(&(FindFileData.cFileName));
I'm not sure if this is correct. I think the cFileName member should be
suitable for use with DeleteFile() without taking its address, even if it
requires a conversion from an array to a pointer. Does this compile without
warnings?
if (0 == rtn)
{
ErrorExit (NULL);
}
Now this again is a completely different error-handling strategy, why? You
might want to invoke FindClose() here, too, btw.
// List all the other files in the directory and delete all files
while (FindNextFile(hFind, &FindFileData) != 0)
{
rtn = DeleteFile(&(FindFileData.cFileName));
}
FindClose(hFind);
}
return 0;
}
The rest here looks correct. However, you could simplify it a bit by using a
do-while-loop:
do {
DeleteFile(..);
} while( FindNextFile(..));
U/i