vector<string> getFilePath(const string& path)
{
vector<string> files;
// 判断dir是文件路径还是目录路径
struct stat path_stat;
if(stat(path.c_str(),&path_stat) == 0)
{
if(S_ISREG(path_stat.st_mode))
{
// dirpath是一个文件的目录
files.push_back(path);
}
else if(S_ISDIR(path_stat.st_mode))
{
// dirname是一个目录
DIR *dirp = opendir(path.c_str());
if (dirp == NULL)
{
cout << "opendir() 打开失败...\n";
exit(-1);
}
struct dirent *pdirent;
while ((pdirent = readdir(dirp)) != NULL)
{
// 去掉.和..
if (string(pdirent->d_name) == "." || string(pdirent->d_name) == "..")
{
continue;
}
// 将路径存入vector<string> _files中
string filepath = path + "/" + string(pdirent->d_name);
// cout << "filepath:" << ++ i << " :" << filepath << "\n";
files.push_back(filepath);
}
// for(size_t j = 0;j < _files.size();)
files.resize(files.size());
// 及时释放资源,关闭目录流
closedir(dirp);
}
}
else
{
perror("stat");
}
return files;
}
该代码仅适用于,某一个目录下全是文件的情况