Linux Directory Listing

Started by
1 comment, last by Kaluriel 15 years, 10 months ago
I've got some code for listing the contents of a directory on linux, but no way of determining if the object is a file or a directory, short of calling opendir each time to check. Just wondered if there are any other ways. Thanks

typedef std::multimap< std::string, std::string > DirectoryList;


void LinuxPlatform::getDirectoryListing( std::string inDirectory, DirectoryList & outList )
{
    struct dirent *dirp;
    DIR *dp;

    if( ( dp = opendir( inDirectory.c_str() ) ) != 0 )
    {
        while( ( dirp = readdir( dp ) ) != 0 )
        {
            if( dirp->d_name[0] != '.' )
            {
                outList.insert( std::make_pair( "File", dirp->d_name ) );
            }
        }

        closedir( dp );
    }
    else
    {
        printf( "Invalid Directory\n" );
    }
}

Advertisement
This is the dirent definition on linux:

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 */};


You want to check if d_type is 4 (DT_DIR). Regular files have d_type 8 (DT_REG). At least that's what my dirent.h here says.

blah :)
Quote:Original post by kolrabi
This is the dirent definition on linux:

*** Source Snippet Removed ***

You want to check if d_type is 4 (DT_DIR). Regular files have d_type 8 (DT_REG). At least that's what my dirent.h here says.


Ah thanks, my mistake, I must have opened the wrong header (/usr/include/linux/dirent.h), didn't know there was a type attribute in the struct.

This topic is closed to new replies.

Advertisement