【发布时间】:2020-04-16 20:12:10
【问题描述】:
我正在使用 opendir 和 readdir 函数在给定目录中搜索包含 .txt 的文件名。
有什么方法可以在不使用循环的情况下通过函数测试certain extension? (目前我必须循环通过de-> d_filename 进行检查,但它们非常复杂,另外我尝试了de->d_type 但它没有返回扩展名)
另外这个函数是返回文件名的名字,我想要的结果是从头获取路径名,有没有类似de->d_fullfilepath?的函数return 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);
}
}
【问题讨论】:
-
new wchar_t(lpszFolder)创建一个 single 字符,并将其初始化为值lpszFolder。你有什么理由不使用std::wstring? -
仅仅因为目录 API 使用字符数组和指针并不意味着您必须效仿。获得名称后,将其复制到
std::wstring并使用糟糕的数组或字符指针完成。 -
感谢 Mr.Someprogrammerdude 和 Mr.PaulMcKenzie,我试过了,它与 wstring 完美配合。
-
更好的选择是使用
<filesystem>library 中的类并让他们为您处理这些细节。在这种情况下,请查看std::filesystem::directory_iterator。 -
嗨,@Remy 先生,我以前见过文件系统,但我发现它与我需要的格式不同:wchar_t *: ` C:\\Users\\MYFOLDER\\Downloads\\ ` 所以我忽略了它:(((。现在我能了。谢谢你的建议!
标签: c++