How can I get the list of files in a directory using C or C++?

前端 未结 27 3786
情书的邮戳
情书的邮戳 2020-11-21 05:30

How can I determine the list of files in a directory from inside my C or C++ code?

I\'m not allowed to execute the ls command and parse the results from

27条回答
  •  生来不讨喜
    2020-11-21 06:21

    I think, below snippet can be used to list all the files.

    #include 
    #include 
    #include 
    
    static void list_dir(const char *path)
    {
        struct dirent *entry;
        DIR *dir = opendir(path);
        if (dir == NULL) {
            return;
        }
    
        while ((entry = readdir(dir)) != NULL) {
            printf("%s\n",entry->d_name);
        }
    
        closedir(dir);
    }
    

    Following is the structure of the struct dirent

    struct dirent {
        ino_t d_ino; /* inode number */
        off_t d_off; /* offset to the next dirent */
        unsigned short d_reclen; /* length of this record */
        unsigned char d_type; /* type of file */
        char d_name[256]; /* filename */
    };
    

提交回复
热议问题