I have an application where I need to open an xml file, modify it, and close it again. When I test the code on a laptop running Windows Vista, it works perfectly, but under Windows XP I can’t even open the file for read/write access:
errno_t _wfopen_s(&inStream, m_fileName, L"r+, ccs = UTF-8");
…without getting an error code 13, “Permission denied” (although the file will open without any problems if I select “r” rather than “r+’ to specify read-only access). Yet the permissions on the file are all set appropriately, as far as I can see, and the file can be opened and modified from the GUI without difficulty.
What could possibly be causing this? Any suggestions would be welcome.
Well, with r+ you will ask for write access to the file. A privilege that is harder to come by, do triple-check that the user account indeed has the write privilege in the folder.
But sounds like you already checked that. The next consideration is sharing. The fopen() function is quite inappropriate on modern multitasking operating systems, it allows any process to access the opened file and both read and write to it. That rarely comes to a good end, especially write sharing can only produce garbage if the processes don’t negotiate access to the file.
That’s why there’s an fopen_s() in the Microsoft CRT, it makes sure that write sharing is denied. It is very rare that you’d want to allow it. When you pass “r” then read sharing is allowed. When you pass “r+” then no sharing is allowed. That can fail if some other process already has the file opened for reading.
You need to find that other process. The SysInternals’ Handle utility can help you find it. Also consider that it might be your own program.
In general, take charge of controlling the sharing yourself, use the _wfsopen() function instead. Note that there’s no secure version for it because none is needed.