How lock a file in windows using c++?

强颜欢笑 提交于 2019-12-10 10:24:57

问题


How can I lock a file in windows to only current thread (no other threads from same process and no other processes) can access (read/write) the file?

If it is possible please tell me some fcntl-like solution (solution which locks file having its descriptor). But in any case other solutions are welcome too.


回答1:


In Windows, you can open a file with exclusive access with the API function CreateFile and specifying 0 as the share mode. More details at this MSDN link, and this MSDN link.




回答2:


Use the WinAPI call LockFile, Here is a example of its use. However this will only protect you from other processes from touching your file, it still lets other threads in the same process use the file.

EDIT: I did not see this was C++ sorry, I only know the inter thread c# solution, however that MSDN link can at least get you started on preventing other processes from touching your file.



来源:https://stackoverflow.com/questions/6832835/how-lock-a-file-in-windows-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!