从可执行文件内修改文件 - XP 中拒绝权限(但 Vista 除外)
我有一个应用程序,我需要打开一个 xml 文件,修改它,然后再次关闭它。当我在运行 Windows Vista 的笔记本电脑上测试代码时,它工作得很好,但在 Windows XP 下我什至无法打开文件进行读/写访问:
errno_t _wfopen_s(&inStream, m_fileName, L"r+, ccs = UTF-8");
...没有收到错误代码 13,“权限被拒绝”(尽管如果我选择“r”而不是“r+”来指定只读访问权限,文件将毫无问题地打开。但据我所知,文件的权限都已正确设置,并且可以打开该文件并可以轻松地从 GUI 进行修改,
这可能是什么原因造成的?欢迎提出任何建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,使用 r+,您将要求对该文件进行写访问。这是一个很难获得的权限,请仔细检查用户帐户是否确实具有该文件夹的写入权限。
但听起来你已经检查过了。下一个考虑因素是共享。 fopen() 函数在现代多任务操作系统上非常不合适,它允许任何进程访问打开的文件并对其进行读取和写入。这很少会有好的结果,特别是如果进程不协商对文件的访问,写共享只会产生垃圾。
这就是 Microsoft CRT 中存在 fopen_s() 的原因,它确保拒绝写入共享。您很少愿意允许这样做。当您传递“r”时,则允许读取共享。当您传递“r+”时,则不允许共享。如果其他进程已经打开该文件进行读取,则可能会失败。
您需要找到其他进程。 SysInternals 的 Handle 实用程序可以帮助您找到它。 还要考虑到它可能是您自己的程序。
一般情况下,您自己负责控制共享,而是使用 _wfsopen() 函数。请注意,它没有安全版本,因为不需要。
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.