简体   繁体   English

C ++锁定文件后读取文件

[英]C++ Read a File after Locking it

I am working on file locking for first time, and couldn't find relevant posts for solution in Google. 我是第一次进行文件锁定,但是在Google中找不到相关的解决方案。

I am locking a file using this code, to lock file. 我正在使用此代码锁定文件,以锁定文件。

ifile = CreateFileW(FileName, GENERIC_READ |  GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

In next line I am trying to open the same file using 在下一行中,我尝试使用打开同一文件

errno_t ErrorNumber = _wfopen_s(FileHandle, FileName, "rb");

The purpose is to lock the file to prevent any other process from writing to it, while this function is reading its contents. 目的是在此功能读取文件内容时锁定文件,以防止其他任何进程写入文件。 I am getting EACCESS : 13 error code when opening the file with "rb". 使用“ rb”打开文件时,我得到EACCESS:13错误代码。

Any ideas why and how to enable reading the file after locking it ? 有什么想法为什么以及如何在锁定文件后启用读取文件?

Thanks Sujatha 感谢Sujatha

To create a "lock file" on Win32 that won't allow other processes to open it: 要在Win32上创建一个“锁定文件”,不允许其他进程打开它:

ifile = CreateFileW(FileName, GENERIC_READ |  GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_FLAG_DELETE_ON_CLOSE, NULL);

CREATE_NEW and 0 for the sharing mode ensures that the file will only be opened by your process and FILE_FLAG_DELETE_ON_CLOSE ensures that it'll be auto-deleted when you close the file or your process (heaven forbid) crashes. CREATE_NEW0 (共享模式)可确保仅由您的进程打开文件,而FILE_FLAG_DELETE_ON_CLOSE可确保在您关闭文件或进程崩溃(禁止上天堂)时将其自动删除。

This is a somewhat clumsy way of achieving cross-process locks on Win32 though. 不过,这是在Win32上实现跨进程锁定的一种比较笨拙的方法。 Shared Mutex's were invented to solve this problem. 发明了共享Mutex来解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM