I am using scandir()
to list PNG images in a given directory:
我使用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);
}
}
The problem is that the code above also lists:
问题是上面的代码还列出了:
.
..
which I want to get rid of. To do that, I have used:
我想摆脱它。为此,我使用了:
return (st.st_mode & S_IFREG);
to list all regular files. However, this returns nothing, whereas & S_IFDIR
returns everything (i.e. directories and files). How can I fix it?
列出所有常规文件。但是,这不返回任何内容,而&S_IFDIR返回所有内容(即目录和文件)。我该如何解决?
1 个解决方案
#1
Try (st.st_mode & S_IFMT) == S_IFREG.
尝试(st.st_mode&S_IFMT)== S_IFREG。
You need to perform the & operation with the file type bit field before comparing it to S_IFREG.
在将其与S_IFREG进行比较之前,需要使用文件类型位字段执行&操作。
There are also macros defined for these types of operations, which you can find here (I'll also list below)
还有为这些类型的操作定义的宏,您可以在这里找到(我也将在下面列出)
S_ISREG(m) is it a regular file?
S_ISDIR(m) directory?
S_ISCHR(m) character device?
S_ISBLK(m) block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m) symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m) socket? (Not in POSIX.1-1996.)
#1
Try (st.st_mode & S_IFMT) == S_IFREG.
尝试(st.st_mode&S_IFMT)== S_IFREG。
You need to perform the & operation with the file type bit field before comparing it to S_IFREG.
在将其与S_IFREG进行比较之前,需要使用文件类型位字段执行&操作。
There are also macros defined for these types of operations, which you can find here (I'll also list below)
还有为这些类型的操作定义的宏,您可以在这里找到(我也将在下面列出)
S_ISREG(m) is it a regular file?
S_ISDIR(m) directory?
S_ISCHR(m) character device?
S_ISBLK(m) block device?
S_ISFIFO(m) FIFO (named pipe)?
S_ISLNK(m) symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m) socket? (Not in POSIX.1-1996.)