C ++ ReadDirectoryChangesW和Boost将dir更改返回为File(OLD NAME)

时间:2017-07-24 09:08:17

标签: c++ boost boost-filesystem readdirectorychangesw

我有一个监视目录以进行更改的应用程序。但是,当我重命名目录时,让目录A进入目录B,而不是我将看到以下输出结果:

File renamed (OLD): C:\A
Directory renamed (NEW): C:\B

虽然我期待输出:

Directory renamed (OLD): C:\A
Directory renamed (NEW): C:\B

在删除目录时也会发生这种情况,提供输出:

File removed: C:\A\test.txt
File modified: C:\A
File removed: C:\A

虽然我期待输出:

File removed: C:\A\test.txt
Directory modified: C:\A
Directory removed: C:\A

我用来获取此输出的代码(使用Boost&#39文件系统)是:

while(true) {
    FILE_NOTIFY_INFORMATION* info = reinterpret_cast<FILE_NOTIFY_INFORMATION*>(p);
    int ret = ::WideCharToMultiByte(CP_ACP, 0, info->FileName, info->FileNameLength / sizeof(WCHAR), FilePathChar, sizeof(FilePathChar), NULL, NULL);
    stringstream FilePathStream;
    FilePathStream << argv[1];
    FilePathStream << "\\";
    FilePathStream << FilePathChar;
    string FilePath = FilePathStream.str();
    cout << FilePath << endl;
    boost::filesystem::path path(FilePath);
    string Type = "File";
    if (boost::filesystem::is_directory(path)) {
        Type = "Directory";
        }
    ofstream myfile;
    myfile.open("changes.txt", std::ios_base::app);
    switch (info->Action) {
        case FILE_ACTION_ADDED:
            myfile << Type << " added: " << FilePath << "\n";
            break;
        case FILE_ACTION_MODIFIED:
            myfile << Type << " modified: " << FilePath << "\n";
            break;
        case FILE_ACTION_REMOVED:
            myfile << Type << " removed: " << FilePath << "\n";
            break;
        case FILE_ACTION_RENAMED_NEW_NAME:
            myfile << Type << " renamed (NEW): " << FilePath << "\n";
            break;
        case FILE_ACTION_RENAMED_OLD_NAME:
            myfile << Type << " renamed (OLD): " << FilePath << "\n";
            break;
        default:
            myfile << Type << " UNDISCOVERED ACTION: " << FilePath << "\n";
            break;
        }
    myfile.close();
    ::memset(FilePathChar, '\0', sizeof(FilePathChar));
    if (!info->NextEntryOffset) break;
    p += info->NextEntryOffset;
    }

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

问题在于,在这两种情况下,您都不会收到通知,直到该目录不再被称为C:\A(因为它已被删除或移动)。所以当你去的时候:

if (boost::filesystem::is_directory(path)) {
    Type = "Directory";
}

is_directory返回false(因此您将Type留给"File"

我建议改为:

const std::string Type = boost::filesystem::is_directory(path)    ? "Directory" :
                         boost::filesystem::is_regular_file(path) ? "File" :
                                                                    "unknown";