• Uncategorized

About c : c-programming—directory-name-from-DIR-struct

Question Detail

from dirent.h we can see that DIR struct is

struct DIR {
    struct dirent ent;
    struct _WDIR *wdirp;

and dirent struct is

struct dirent {
    /* Always zero */
    long d_ino;

    /* File position within stream */
    long d_off;

    /* Structure size */
    unsigned short d_reclen;

    /* Length of name without \0 */
    size_t d_namlen;

    /* File type */
    int d_type;

    /* File name */
    char d_name[PATH_MAX+1];

My question is: If we have only DIR * struct -let say dir -and from this struct we want to extract directory name, normally we -should? – do:

const char * dirname = dir->ent.d_name;

however this not compile, error is:

dereferencing pointer to incomplete type


Question Answer

You shouldn’t be accessing the contents of a DIR directly.

To iterate through the entries in a directory, you need to call readdir, passing it a DIR * that was returned from opendir. This will return a dirent * from which you can read the name of the directory entry.

The function will return NULL when all entries have been read.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.