C++ ReadDirectoryChangesW 和 Boost 将目录更改作为文件(旧名称)返回

标签 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 的文件系统)是:

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;
    }

我在这里做错了什么?

最佳答案

问题是,在这两种情况下,您都不会收到通知,直到目录不再称为 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";

关于C++ ReadDirectoryChangesW 和 Boost 将目录更改作为文件(旧名称)返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45276483/

相关文章:

c++ - QTcpSocket 的 QThread 没有发出完成信号

c++ - ->Release() 是在 COM 对象的析构函数上调用的吗?

c++ - 对静态/隐式链接与动态/显式链接的误解

c++ - (如何)我可以将 Boost 字符串算法库与 c 字符串(字符指针)一起使用?

c++ - 如何在任何文件的元数据中存储用户定义的字段?

c++ - boost::filesystem 添加引号?

c++ - Boost.Filesystem 崩溃

c++ - VisualStudio 和 gcc 之间 *.dll *.a *.lib *.def 的兼容性

c++ - 智能指针问题

c++ - 链接qt lib错误