Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 578
Phiber Avatar asked Oct 31 '25 07:10

Phiber


1 Answers

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.

like image 185
dbush Avatar answered Nov 03 '25 00:11

dbush