Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to get a file list into an array of files ?

Status
Not open for further replies.

OhNoNotAgain

Programmer
May 21, 2003
6
AU
All,

Newish to C. On a UNIX box I want to execute an ls command and capture the files in an array of filenames.

Can someone please recommend a method and/or a good site for this type of function for Unix.

Thanks
 
Something like this?

Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


#define MAXLINES 15000
#define MAXLEN 250
char bufnames[MAXLINES][MAXLEN];

int main(int argc, char **argv) {
int y = 0;
FILE *pp;

     if (argc < 2) {
        printf(&quot;Error: need command name string\n&quot;);
        exit(1);
     }


     pp = popen(argv[1],&quot;r&quot;);

        if (!pp) {
            perror(&quot;popen()&quot;);
            exit(1);
        } else {
           while ( (fgets(bufnames[y],MAXLEN,pp)) != NULL) {
                    printf(&quot;%d: %s\n&quot;, y, bufnames[y]);
                    y++;
           }
        pclose(pp);
        } 

        
   
return 0;
}

Then you can use whatever command you want to
get the output you need.
I suggest find dirname -type f instead of ls.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top