我正在使用opendir和readdir函数在给定目录中搜索包含.txt的文件名。
有什么方法可以通过函数而不使用循环来测试certain extension
? (当前,我必须遍历de-> d_filename
进行检查,但它们相当复杂,此外,我尝试了de->d_type
,但未返回扩展名)
另外,此函数返回文件名的名称,我想要的结果是从头开始获取路径名,是否存在类似于de->d_fullfilepath?
的函数返回wchar_t *
这就是我所拥有的:
DIR* dr = opendir(lpszFolder);
vector<const wchar_t*> names; //get list file with extension .txt then push to this vector
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory");
return {};
}
// Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html
// for readdir()
while ((de = readdir(dr)) != NULL)
{
if (de->d_type ... 'txt') // function get just .txt file.
{
wchar_t* pwc =new wchar_t(lpszFolder); //initialize new instance file path
const size_t cSize = de->d_namlen + 1; //get file len
mbstowcs(pwc, de->d_name, cSize); //combine thisfilepath + extension
names.push_back(pwc);
}
}
最佳答案
最佳Libc功能可反向搜索
您可能会考虑strrchr
Locate last occurrence of character in string Returns a pointer to the last occurrence of character in the C string str.
The terminating null-character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string.
示例程序以查找具有特定文件扩展名的文件
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <string>
#include <vector>
using namespace std;
const char *get_filename_ext(const char *filename) {
const char *dot = strrchr(filename, '.');
return (!dot || dot == filename) ? "" : dot + 1;
}
int main(int ac, char **av) {
if (ac != 2)
return 1;
const char *lookup = (ac==3) ? av[2] : "txt";
const char *lpszFolder = av[1];
DIR* dr = opendir(lpszFolder);
vector<const wchar_t*> names; //get list file with extension .txt then push to this vector
if (dr == NULL) // opendir returns NULL if couldn't open directory
{
printf("Could not open current directory");
return (1);
}
struct dirent *ent;
uint32_t len = sizeof(((dirent*)0)->d_name);
char ext[len];
while ((ent = readdir (dr)) != NULL) {
(void)ext;
strncpy(ext, get_filename_ext(ent->d_name), len-1);
if (!strcmp(lookup, ext))
names.push_back(reinterpret_cast < wchar_t*>(ent->d_name));
}
closedir(dr);
for (auto name : names)
printf("%s", (char *)name);
return 0;
}
主要用途
测试:
g++ a.cpp && ./a.out myfolder
将查找所有扩展名为“.txt”的文件
或者,如果您想要像☠这样的特定扩展名:
g++ a.cpp && ./a.out myfolder ☠
关于c++ - 如何在C++中检查char数组是否包含任何不带循环的char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61259221/