[代码实例][Linux系统编程]列出目录下的文件和子目录

系统调用


#include 

DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);

代码实例


#include 
#include 
#include 
#include 
#include 

#include 

void list_files(const char * dir_path);

int main(int argc, char * argv[])
{
    if(argc > 1 && strcmp(argv[1], "--help") == 0)
    {
        printf("Usage: %s [dir...]\n", argv[0]);
        return EXIT_SUCCESS;
    }

    if(argc == 1)
        list_files(".");
    else
        for(int i = 1; i < argc; i++)
            list_files(argv[i]);

    return EXIT_SUCCESS;
}

void list_files(const char * dir_path)
{
    DIR * dirp;
    struct dirent * dp;
    bool is_current;

    is_current = strcmp(dir_path, ".") == 0;

    if((dirp = opendir(dir_path)) == NULL)
    {
        perror("opendir");
        exit(EXIT_FAILURE);
    }

    while(true)
    {
        errno = 0;
        if((dp = readdir(dirp)) == NULL)
            break;

        if(strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
            continue;

        if(!is_current)
        {
            printf("%s/", dir_path);
        }

        printf("%s\n", dp->d_name);
    }
}

你可能感兴趣的:(代码实例)