And finally, you could try opening your file with exclusive access -
std::ifstream file(sFile, std::ifstream::in, _SH_DENYRW);
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have the following code:
{
std::string line{};
std::ifstream file(sFile, std::ifstream::in);
TRACE("Openning %S\n", sFile);
if (file)
{
while (std::getline(file, line))
{
// do something here
}
}
}
BOOL b = DeleteFile(sFile);
TRACE("+++%d|%d|%x\n", b, GetLastError(), GetLastError());
The file itsn't deleted, and the output of these TRACEs are:
Openning C:\Temp\MyFile.tmp
+++0|32|20
Which means:
ERROR_SHARING_VIOLATION
32 (0x20)
The process cannot access the file because it is being used by another process.
Of course, I don't touch that file with something else ... What could be the problem here ?
And finally, you could try opening your file with exclusive access -
std::ifstream file(sFile, std::ifstream::in, _SH_DENYRW);
If the file was opened successfully then the destructor for the ifstream object should close the file when it goes out of scope. If there is still an open handle to the file it may be antivirus or some other process on your system. Process Explorer can identify the process holding an open handle to your file.
Hi,
Try to close the file before deleting it.
... ...
file.close();
BOOL b = DeleteFile(sFile);
Best regards,
Minxin Yu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
In addition to Process Explorer you can use Process Monitor to track all file system usage for your target file. This is another way to identify a process other than your own that is using the target file when you attempt to delete it.
Updated to add images from Process Monitor and Process Explorer
Process Monitor -
Process Explorer -