我已经使用 LockFileEx
锁定了一个文件,但我无法打开其中的流。
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;
}
}
获取锁后,我想这样做:
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;
}
我这样做是因为我发现使用流逐行阅读更容易...
有解决办法吗?
最佳答案
来自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.
因此您需要使用已有的句柄,而不是创建一个新句柄。
_open_osfhandle函数允许您从现有句柄创建文件描述符,然后您可以将此文件描述符传递给 ofstream constructor而不是文件名。
关于c++ - 使用 Windows C++ LockFIle() 锁定文件然后从中获取流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24664046/