Im using the CreateFile api and some times it randomly fails with the error: ERROR_SHARING_VIOLATION.
I have googled and there is almost nothing about this error. The strange thing is next time it is quite happy to open the same file.
Here is my code:
void FileHandle::open(const char* fileName, FILE_MODE mode)
{
if (m_bIsOpen)
close();
HANDLE fh = NULL;
DWORD dwDesiredAccess = GENERIC_READ;
DWORD dwShareMode = FILE_SHARE_READ;
DWORD dwCreationDisposition = OPEN_EXISTING;
switch (mode)
{
case FILE_READ:
break;
case FILE_WRITE:
dwDesiredAccess = GENERIC_WRITE;
dwShareMode = 0;
dwCreationDisposition = CREATE_ALWAYS;
break;
case FILE_APPEND:
dwDesiredAccess = GENERIC_WRITE;
dwShareMode = 0;
dwCreationDisposition = OPEN_ALWAYS;
break;
default:
throw gcException(ERR_INVALID, "The mode was invalid");
break;
}
fh = CreateFile(fileName, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, 0, NULL);
if (!fh || fh == INVALID_HANDLE_VALUE)
throw gcException(ERR_INVALIDFILE, GetLastError(), gcString("Failed to open the file {0}", fileName));
m_hFileHandle = fh;
m_bIsOpen = true;
if (mode == FILE_APPEND)
{
DWORD high = 0;
DWORD low = GetFileSize(fh, &high);
uint64 pos = (((uint64)high)<<32) + (uint64)low;
seek(pos);
}
}
Am i doing something wrong or is there an issue with the api?
Edit: Im using the full file name (i.e. C:\somefile.txt) and mode=FILE_WRITE
There is nothing wrong with CreateFile - a sharing violation means that something else has the same file open. Which could be your own program, if you have the file open with a share mode of 0, you won't be able to open it again.
Sometimes an AV's (or other software that monitors files) operations and timing can cause sharing conflicts. This is particularly true if you're opening an existing file for exclusive access (this would be the case for the FILE_WRITE and FILE_APPEND cases if the file already exists).
not need the FILE_SHARE_WRITE. Thanks for the help! I have a program that writes continuously to a text file. The program from time to time for monitoring it's status. other windows applications all come back with sharing violations. FILE_SHARE_WRITE in order to open the file.
There is nothing wrong with CreateFile - a sharing violation means that something else has the same file open. Which could be your own program, if you have the file open with a share mode of 0, you won't be able to open it again.
When you get the error you can use Process Explorer to determine what processes have the file open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With