【发布时间】:2015-05-10 22:20:54
【问题描述】:
我正在使用scandir() 列出给定目录中的 PNG 图像:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int file_select(const struct dirent *entry)
{
struct stat st;
stat(entry->d_name, &st);
return (st.st_mode & S_IFREG); // This doesn't work
/* return (st.st_mode & S_IFDIR); */ // This lists everything
}
int num_sort(const struct dirent **e1, const struct dirent **e2) {
char* pch = strtok ((char*)(*e1)->d_name,".");
char* pch2 = strtok ((char*)(*e2)->d_name,".");
const char *a = (*e1)->d_name;
const char *b = (*e2)->d_name;
return atoi(b) > atoi(a);
}
int main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, file_select, num_sort);
if (n < 0) {
perror("scandir");/
} else {
while (n--) {
printf("File:%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
}
}
问题是上面的代码也列出了:
.
..
我想摆脱它。为此,我使用了:
return (st.st_mode & S_IFREG);
列出所有常规文件。但是,这不会返回任何内容,而 & S_IFDIR 会返回所有内容(即目录 和 文件)。我该如何解决?
【问题讨论】:
-
您只需要检查名称字符串。如果是
.或..,则返回false。 -
if( strcmp(namelist[n]->d_name, ".") && strcmp(namelist[n]->d_name, "..") ) printf("File:%s\n", namelist[n]->d_name);是你想要的吗? -
@AndrewMedico 谢谢,但我仍然不明白为什么
S_IFREG不起作用。 -
@BlueMoon 不完全是,但我在
file_select()中添加了类似的内容,因此namelist将只包含我想要的条目。 -
我不明白为什么
S_IFREG不应该工作。但这将排除比您想要的更多的文件。您想要的只是排除.和..,那么一个简单的条件就足够了。S_IFDIR也可以使用(如果您想排除所有目录)。