【问题标题】:Find *.txt files in directory c++ [duplicate]在目录c ++中查找* .txt文件[重复]
【发布时间】:2018-05-14 14:45:33
【问题描述】:

我想使用 c++ 从目录中获取 txt 文件。我在谷歌搜索并找到“dirent.h”,但我不能使用这个库。它给了我一个 C1083 故障。这是我的代码。我已经包含了 fstream,dirent.h vs...

ifstream fin;
string dir, filepath;
int num;
DIR *dp;
struct dirent *dirp;
struct stat filestat;

cout << "dir to get files of: " << flush;
getline(cin, dir);  

dp = opendir(dir.c_str());
if (dp == NULL)
{
    cout << "Error(" << errno << ") opening " << dir << endl;
    return errno;
}

while ((dirp = readdir(dp)))
{
    filepath = dir + "/" + dirp->d_name;


    if (stat(filepath.c_str(), &filestat)) continue;
    if (S_ISDIR(filestat.st_mode))         continue;


    fin.open(filepath.c_str());
    if (fin >> num)
        cout << filepath << ": " << num << endl;
    fin.close();
}

`

【问题讨论】:

  • 我不知道你是否可以使用 C++17,但如果可以,那么你将可以访问标准库中的文件系统库。
  • 您是否尝试过查找C1083?你如何包含相应的标题?
  • 在 C++17 之前,有提升。比 dirent 容易得多。

标签: c++ file directory


【解决方案1】:

什么是使用 boost ? 例如(待查):

int     filter_txt_files (std::string offset,std::vector<std::string>& vec_res)
{  
    boost::system::error_code ec;
    boost::filesystem::path offset_path(offset);

    for (boost::filesystem::directory_iterator it (offset_path, ec), eit;
         it != eit;
         it.increment (ec)
         )
    {
        if (ec)
            continue;

        if (boost::filesystem::is_regular_file (it->path ()))            
        {
            if(it->path ().extension ().string () == "txt")
                vec_res.push_back(it->path ().string());
        }
        // if you need recursion
        else if (boost::filesystem::is_directory (it->path ()))
        {
            filter_txt_files(it->path ().string(),vec_res);
        }
    }
    return ((int)vec_res.size());
}

【讨论】:

    【解决方案2】:

    您使用的函数来自 POSIX 标准,未在 Windows 上实现。

    如果您需要可移植的 C++ 解决方案,唯一的方法是使用 C++17 filesystem library - 但在 Visual Studio 2015 及更早版本中未实现。

    另一种解决方案是使用Boost,更准确地说是Boost.Filesystem 库。

    两种解决方案都不处理通配符,因此您必须自己实现过滤,可能使用std::regex

    您还可以使用原生 Windows API 函数 FindFirstFileFindNextFileFindClose - 这些函数支持通配符。 MSDN 有一个 example 说明如何使用它们。

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 2013-11-30
      • 2016-10-17
      • 1970-01-01
      • 2011-07-05
      相关资源
      最近更新 更多