boost :: filesystem获取当前目录中的所有文件-Windows

问题描述

我有一个qt应用程序,它使用以下实用程序功能获取给定目录路径中的文件列表。

void listTopLevelFiles(const boost::filesystem::path& directoryPath,std::vector<std::string> &topLevelFiles) {
    if (!exists(directoryPath))
        return;
    //non-recursive directory iterator
    boost::filesystem::directory_iterator end_itr;
    for (boost::filesystem::directory_iterator itr(directoryPath); itr != end_itr; ++itr) {
        bool selectEntry = boost::filesystem::is_regular_file(itr->status());
        if (selectEntry && (itr->path().parent_path() == directoryPath)) {
            topLevelFiles.push_back(itr->path().string());
        }
    }
}

但是,从度量标准用法来看,我发现对于某些用户,在某些情况下,topLevelFiles向量为空。在某些情况下,我的意思是以下情况

  • 通过获取顶级文件,该应用程序可以正常运行
  • (*一段时间后*)重新打开应用,矢量大小为0(应用崩溃)
  • 大小为0表示连续多次重新打开(应用程序崩溃)
  • 用户做了一些魔术-重新启动机器吗?!)应用程序起作用-正确填充了顶层文件

不幸的是,我无法在Windows机器上重现此错误。需要注意的一点是,此应用程序的mac用户不会发生此问题。

应用程序上下文:在主.exe所在的文件夹内,某些数据文件与应用程序捆绑在一起。这些文件使用std :: ifstream读取,并复制到字符串流中。

鉴于该问题是暂时的,仅在Windows中发生,我怀疑Windows中臭名昭著的文件锁定会造成麻烦。 (该应用程序的先前实例是否打开了某些文件句柄?)

从上面的函数获取矢量之后,有一些代码片段与这些数据文件发生的事情有关

bool createFileStream(const std::string& filePathUTF8,std::unique_ptr<std::ifstream>& fileStream) {
    // Windows doesn't accept filenames encoded in UTF8. convert to wide string.
    std::wstring filePathW = StringUtils::getWString(filePathUTF8);
    std::ifstream* file = new std::ifstream(filePathW);
    if(file->is_open()) {
        fileStream.reset(file);
        return true;
    }
    return false;
}

bool decryptFileStream(std::unique_ptr<std::ifstream> inputFileStream,std::unique_ptr<std::istream>& outputIStream) {
    if(inputFileStream == nullptr)
        return false;
    //Get the length of the file stream
    inputFileStream->seekg(0,std::ios::end);
    size_t length = static_cast<size_t>(inputFileStream->tellg());

    inputFileStream->seekg(0,std::ios::beg);
    inputFileStream->clear();
    //Check that the file stream is in good state
    if (!inputFileStream->good())
        return false;
    //Decrypt the file stream into a stringstream
    {
        std::unique_ptr<char[]> buffer;
        buffer.reset(new char[length]);
        //Decrypt the file stream
        int64_t readSize = decryptFileStreamFromOffset(inputFileStream.get(),length,(uint8_t *)buffer.get());
        if(readSize == length) {
            outputIStream.reset(new std::istringstream(std::string(buffer.get(),length)));
            return true;
        }
    }
    return false;
}

我做错了什么是不好的做法,势必会引起问题?我应该如何进行?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)