简体   繁体   中英

Listing files in a given directory on Linux

I am using scandir() to list PNG images in a given directory:

#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 (ie directories and files). How can I fix it?

Try (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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM