gpt4 book ai didi

c++ - 在c++目录中查找*.txt文件

转载 作者:行者123 更新时间:2023-12-03 12:49:06 24 4
gpt4 key购买 nike

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

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

`

最佳答案

使用 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());
}

关于c++ - 在c++目录中查找*.txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com