MFC CFile::Open Flags
-
I recently had a problem reported to me where, seemingly at random, a service application was failing to open a file, with an "Access denied" error being logged. The application in question relies heavily on threads. I eventually traced the problem to the following line of (MFC) code:
CFile file;
file.Open(lpszFileName, CFile::modeRead);
...The problem occurred when two threads attempted to open the same file at the same time. The bug? I'd forgotten to add any share flags! This meant that if thread A opened the file for reading, thread B would then fail. Ack. I guess I am used to using STL streams (such as
std::ifstream
), which, by default, will allow other processes/threads to open a file by specifying a more useful default share mode. To fix the bug I had to add a flag such asCFile::shareDenyWrite
, so other processes could still open the file for reading.CFile file;
file.Open(lpszFileName, CFile::modeRead|CFile::shareDenyWrite);
...This may be obvious, but to a noob, or to someone that hasn't used MFC or Win32
::CreateFile
in a long time, it might bite you on the backside too. :)
Kicking squealing Gucci little piggy.
-
I recently had a problem reported to me where, seemingly at random, a service application was failing to open a file, with an "Access denied" error being logged. The application in question relies heavily on threads. I eventually traced the problem to the following line of (MFC) code:
CFile file;
file.Open(lpszFileName, CFile::modeRead);
...The problem occurred when two threads attempted to open the same file at the same time. The bug? I'd forgotten to add any share flags! This meant that if thread A opened the file for reading, thread B would then fail. Ack. I guess I am used to using STL streams (such as
std::ifstream
), which, by default, will allow other processes/threads to open a file by specifying a more useful default share mode. To fix the bug I had to add a flag such asCFile::shareDenyWrite
, so other processes could still open the file for reading.CFile file;
file.Open(lpszFileName, CFile::modeRead|CFile::shareDenyWrite);
...This may be obvious, but to a noob, or to someone that hasn't used MFC or Win32
::CreateFile
in a long time, it might bite you on the backside too. :)
Kicking squealing Gucci little piggy.