Thread: finding files in a directory

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    44

    finding files in a directory

    I was just curious as to how I would run through the files in a directory and print out each file name.

    thanks.
    [Strut]

    I lay on my bed watching the stars, and I thought to myself... Where the hell is my roof?

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    202
    ls -a on the command line.

    Are you looking to do this in a script or a compiled program?

    starX
    www.axisoftime.com

  3. #3
    junior member mix0matt's Avatar
    Join Date
    Aug 2001
    Posts
    144
    read the man page ($man scandir) for scandir. That should give you the info you want for your system.

    Code:
    int scandir (const char *dir, struct direct ***namelist, 
                                      int (*select) (const struct direct *),
                                      int (*compar) (const struct direct **, const struct direct **));
    here's a rough example (notethat if select is passed a NULL arguement, all names under the directory are placed in the arrary of direct structures.

    Code:
    #include <sys/dir.h>
    #include <sys/param.h>
    #include <stdio.h>
    #include <string.h>
    
    extern int alphasort ();
    
    char pathname[MAXPATHLEN];
    
    int main ()
    {
        int count, i;
        struct direct** files;
    
        strcpy (pathname, "/home/matt");
        count = scandir (pathname, &files, NULL, alphasort);
        if (count <= 0) {
            fprintf (stderr, "No files in the directory \n");
            exit (0);
        }
        printf ("Number of files = %d\n", count);
        for (i = 1; i < count + 1; ++i )
            printf ("%s\n", files[i-1]->d_name);
    
        return 0;
    }
    Let me know if you don't understand anything after you read the man page...

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    44
    thanks to both of you!
    [Strut]

    I lay on my bed watching the stars, and I thought to myself... Where the hell is my roof?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to extract a list of files in a specific directory?
    By Perspektyva in forum C++ Programming
    Replies: 4
    Last Post: 11-11-2008, 02:02 PM
  2. Finding files question
    By geek@02 in forum Windows Programming
    Replies: 12
    Last Post: 09-02-2008, 03:31 AM
  3. Copying all files in a directory
    By rak1986 in forum C Programming
    Replies: 2
    Last Post: 08-25-2008, 01:02 AM
  4. deleting all files in a directory using c..
    By ShadeS_07 in forum C Programming
    Replies: 6
    Last Post: 07-30-2008, 08:21 AM
  5. R/W on files in a directory by i-number
    By Lateralus in forum Linux Programming
    Replies: 1
    Last Post: 07-26-2005, 10:58 AM