在Windows上使用C ++锁定文件 [英] Locking files using C++ on Windows
问题描述
我有一个程序可以从文件中读写文件,并且我想为我的应用程序的其他实例锁定文件.我该怎么做(在C ++ Visual Studio 2003中)? 我尝试使用_locking(),但是在尝试读写(在同一实例中)时,我自己也无法访问该文件. 我知道有一个LockFile()选项,但不知道如何正确设置它. 请帮助我.
I have a program writing/reading from a file, and I want to lock the file for other instances of my application. How can I do it (in c++ visual studio 2003)? I tried using the _locking() but then also I myself cannot reach the file when trying to read/write (in the same instance). I know there's an option of LockFile() but have no idea how to set it properly. Please help me.
推荐答案
You can simply use the Win32 API CreateFile and then specify no sharing rights. This will ensure that no other processes can access the file.
dwShareMode DWORD指定您想要的共享类型,例如GENERIC_READ.如果您指定0,则表示不应授予任何共享权限.
The dwShareMode DWORD specifies the type of sharing you would like, for example GENERIC_READ. If you specify 0 then that means no sharing rights should be granted.
示例:
HANDLE hFile = CreateFile(_T("c:\\file.txt"), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
如果只想锁定文件的特定部分,则可以使用 LockFile 或 LockFileEx .
示例:
//Lock the first 1024 bytes
BOOL bLocked = LockFile(hFile, 0, 0, 1024, 0);
这篇关于在Windows上使用C ++锁定文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!