All files in a directory

This is a discussion on All files in a directory within the Linux Programming forums, part of the Platform Specific Boards category; Hi All, I want to be able to iterate through a directory finding files with a specific file extension, like ...

  1. #1
    Registered User
    Join Date
    Oct 2004
    Posts
    100

    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++.

    Thanks

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

    Code:
    #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);
            }
        }
        closedir(dir);
    }
    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, 10: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21