Jump to content
  • Advertisement
Sign in to follow this  
Kaluriel

Linux Directory Listing

This topic is 3665 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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" );
    }
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!