2

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?

Drew McGowen
  • 11,471
  • 1
  • 31
  • 57
saurabh daga
  • 205
  • 1
  • 2
  • 11

2 Answers2

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.

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
  • The ofstream constructor is not accepting the file descriptor as a constructor argument ... Can you please help me with that? – saurabh daga Jul 10 '14 at 15:40
  • 1
    It seems this has changed since VS6, and is no longer supported. This is unfortunate; I have no idea why we've lost such basic functionality. Perhaps the [answers to this question](http://stackoverflow.com/questions/2746168/how-to-construct-a-c-fstream-from-a-posix-file-descriptor) might help. – Harry Johnston Jul 10 '14 at 22:01
0

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.

Erik
  • 88,732
  • 13
  • 198
  • 189