c - 如何检查文件是否已被 C 中的另一个进程打开?

标签 c windows file

我看到标准 C 无法判断文件是否已在另一个进程中打开。所以答案应该包含每个平台的几个例子。不过,我需要检查 Visual C++/Windows。

最佳答案

Windows:尝试以独占模式打开文件。如果有效,则没有其他人打开过该文件,将无法打开该文件

HANDLE fh;
fh = CreateFile(filename, GENERIC_READ, 0 /* no sharing! exclusive */, NULL, OPEN_EXISTING, 0, NULL);
if ((fh != NULL) && (fh != INVALID_HANDLE_VALUE))
{
   // the only open file to filename should be fh.
   // do something
   CloseHandle(fh);
}

MS 说:dwShareMode

The sharing mode of an object, which can be read, write, both, delete, all of these, or none (refer to the following table).

If this parameter is zero and CreateFile succeeds, the object cannot be shared and cannot be opened again until the handle is closed.

You cannot request a sharing mode that conflicts with the access mode that is specified in an open request that has an open handle, because that would result in the following sharing violation: ERROR_SHARING_VIOLATION.

http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx

扩展名: 如何删除一个没有人打开读/写的(非只读的)文件系统?

访问权限 FILE_READ_ATTRIBUTES,而不是 DELETE。 DELETE 可能会导致 smb 共享(对 MS Windows 服务器)出现问题 - CreateFile 将留下一个仍然打开的 FileHandle/Device/Mup:xxx 文件名 - 为什么这个 Mup 是什么。访问权限 FILE_READ_ATTRIBUTES 不会发生 使用 FILE_FLAG_OPEN_REPARSE_POINT 删除文件名。否则您将删除符号链接(symbolic link)的目标 - 这通常不是您想要的

HANDLE fh;
fh = CreateFile(filename,  FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE /* no RW sharing! */, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_DELETE_ON_CLOSE, NULL);
if ((fh != NULL) && (fh != INVALID_HANDLE_VALUE))
{
    DeleteFile(filename); /* looks stupid?
                          * but FILE_FLAG_DELETE_ON_CLOSE will not work on some smb shares (e.g. samba)!
                          * FILE_SHARE_DELETE should allow this DeleteFile() and so the problem could be solved by additional DeleteFile()
                          */
    CloseHandle(fh); /* a file, which no one has currently opened for RW is delete NOW */

} 

如何处理打开的文件?如果文件已打开并且您被允许取消链接,您将留下一个文件,随后打开该文件将导致 ACCESS_DENIED。 如果您有一个临时文件夹,那么重命名(文件名,tempdir/filename.delete)并删除 tempdir/filename.delete 可能是个好主意。

关于c - 如何检查文件是否已被 C 中的另一个进程打开?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1951791/

相关文章:

c - 如何等待子进程发送信号?

c - 向二维数组中的结构成员添加值时出现未处理的异常

windows - 不能将 git add 与 --patch 选项一起使用

file - 什么是文件句柄以及它对程序员有用的地方?

c++ - 将文本文件的内容 append 到C++中的另一个文件

c++ - 将一行文件读入一个对象中的2个变量

c - 如何检查打开的文件是否已被另一个进程移动或删除

c++ - if(x==y==z) 有效,if(x!=y!=z) 无效

c++ - VS 2010 中 win32 应用程序中的文件夹复制

windows - dotNerInstaller 问题出现错误 "The installation package could not be opened. Verify..."