Phiber
Phiber

Reputation: 1103

c programming - directory name from DIR* struct

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

Thanks

Upvotes: 4

Views: 17749

Answers (1)

dbush
dbush

Reputation: 223739

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.

Upvotes: 8

Related Questions