如何检查文件是否正在被另一个应用程序使用

如何检查文件是否正在被另一个应用程序使用

本文介绍了如何检查文件是否正在被另一个应用程序使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来检查文件是否正在被另一个应用程序使用:

I am using the following code to check if a file is being used by another application:

HANDLE fh = CreateFile("D:\\1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
    MessageBox(NULL, "The file is in use", "Error", 0);
}

如果文件正被另一个应用程序使用,则会显示消息框.但是,如果文件不存在,也会显示消息框!

If the file is being used by another application, the message box is displayed. However, the message box is also displayed if the file does not exists!

那么我应该怎么做才能解决这个问题,我应该也检查文件是否存在(使用另一个函数),还是可以将CreateFile()的参数更改为只返回INVALID_HANDLE_VALUE 如果文件正在使用并且确实存在?

So what should I do to solve this problem, should I also check if the file exists (using another function), or can the parameters of CreateFile() be changed to only return INVALID_HANDLE_VALUE if the file is in use and does exists?

推荐答案

你需要使用 GetLastError() 来知道为什么 CreateFile() 失败,例如:>

You need to use GetLastError() to know why CreateFile() failed, eg:

// this is requesting exclusive access to the file, so it will
// fail if the file is already open for any reason. That condition
// is detected by a sharing violation error due to conflicting
// sharing rights...

HANDLE fh = CreateFile("D:\\1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
    switch (GetLastError())
    {
        case ERROR_PATH_NOT_FOUND:
        case ERROR_FILE_NOT_FOUND:
            MessageBox(NULL, "The file does not exist", "Error", 0);
            break;

        case ERROR_SHARING_VIOLATION:
            MessageBox(NULL, "The file is in use", "Error", 0);
            break;

        //...

        default:
            MessageBox(NULL, "Error opening the file", "Error", 0);
            break;
    }
}
else
{
    // the file exists and was not in use.
    // don't forget to close the handle...
    CloseHandle(fh);
}

这篇关于如何检查文件是否正在被另一个应用程序使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 10:46