[英]how to list all the .txt files in the current directory?
我确实知道如何通过打开目录"./"
然后使用readdir
从当前目录读取所有文件。 但是,如何仅列出.txt
文件或任何其他特定的扩展名?
DIR *p;
struct dirent *pp;
p = opendir ("./");
if (p != NULL)
{
while ((pp = readdir (p))!=NULL)
puts (pp->d_name);
(void) closedir (pp);
}
只需在打印前检查文件名即可。
DIR *p;
struct dirent *pp;
p = opendir ("./");
if (p != NULL)
{
while ((pp = readdir (p))!=NULL) {
int length = strlen(pp->d_name);
if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0) {
puts (pp->d_name);
}
}
(void) closedir (p);
}
顺便说一句,您也在调用dirent
(pp)而不是DIR *
(p)来调用closedir()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.