Thread: All files in a directory

  1. #1
    Registered User
    Join Date
    Oct 2004

    All files in a directory

    Hi All,

    I want to be able to iterate through a directory finding files with a specific file extension, like searching /home/username for all .sh files.

    The language im using is C++.


  2. #2
    Registered User
    Join Date
    Apr 2007
    Sydney, Australia
    Well i guess you could use the directory reading functions in the POSIX c library.

    #include <stdio.h>
    #include <stdlib.h>
    #include <dirent.h>
    #include <sys/stat.h>
    void ListFiles(const char* path)
        DIR *dir;
        struct stat statx;
        struct dirent *ent;
        if ((dir = opendir(path)))
            while ((ent = readdir(dir)))
                char fullName[1024];
                strncpy(fullName, path, sizeof(fullName));
                strncat(fullName, ent->d_name, sizeof(fullName));
                stat(fullName, &statx);
                if (!(statx.st_mode & S_IFDIR))  //remove this if you also want to list sub directories
                    printf("&#37;s\n", fullName);
    I havnt tested it but that should list all the files in a directory. You can use ent->d_name and check it's extension.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading .dat files from a folder in current directory...
    By porsche911nfs in forum C++ Programming
    Replies: 7
    Last Post: 04-04-2009, 09:52 PM
  2. Couple errors please help :-D
    By JJJIrish05 in forum C Programming
    Replies: 9
    Last Post: 03-06-2008, 02:54 AM
  3. Replies: 9
    Last Post: 12-19-2006, 04:23 PM
  4. Listing files in a directory.
    By Devil Panther in forum C++ Programming
    Replies: 5
    Last Post: 11-04-2006, 09:39 PM
  5. Reading files in a directory
    By roktsyntst in forum Windows Programming
    Replies: 5
    Last Post: 02-07-2003, 10:04 AM