在Windows上使用C ++锁定文件 [英] Locking files using C++ on Windows

查看:176
本文介绍了在Windows上使用C ++锁定文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以从文件中读写文件,并且我想为我的应用程序的其他实例锁定文件.我该怎么做(在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.

推荐答案

您可以简单地使用Win32 API

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆