Lock a file using windows c++ LockFIle() then get a stream from it?

北城余情 提交于 2019-12-07 20:01:53

问题


I have locked a file using LockFileEx, but I am not able to open a stream from it.

HANDLE indexHandle = CreateFile (indexFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, 
        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

bool indexLock = false;
OVERLAPPED overlapped;
memset (&overlapped, 0, sizeof (overlapped));
while (noOfTries >0 && !indexLock)
{
   if (!LockFileEx (indexHandle, LOCKFILE_EXCLUSIVE_LOCK, 0, 0, UINT_MAX, &overlapped))
   {
      InfoLog << "Failed to get lock on index file  -- Error code is ["
            << GetLastError () <<"]"<<std::endl;
      Sleep(sleepTime);
      noOfTries--;

   }
   else
   {
      indexLock=true;    
   }
}

After the lock is acquired, I want to do this:

string indexFile = mPath + Util::PATH_SEPARATOR + mIndexFileName;
os.open( indexFile.c_str(), ios_base::app);
if (!os)
{
  InfoLog << "BinaryFileSystemObjectStore:: ofstream: Failed to open index for write: " << indexFile.c_str() << endl;
}

I do this because I find it easier to read line by line with streams...

Is there a solution?


回答1:


From the documentation for LockFileEx:

If the locking process opens the file a second time, it cannot access the specified region through this second handle until it unlocks the region.

So you need to use the handle you already have rather than creating a new one.

The _open_osfhandle function allows you to create a file descriptor from an existing handle, and you can then pass this file descriptor to the ofstream constructor instead of the filename.




回答2:


You open the file with FILE_SHARE_READ. This means you permit further opening of the file for reading only. Then you try to open it for writing, which will fail.

Use FILE_SHARE_READ | FILE_SHARE_WRITE instead.



来源:https://stackoverflow.com/questions/24664046/lock-a-file-using-windows-c-lockfile-then-get-a-stream-from-it

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