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!

Reading contents of a directory

Status
Not open for further replies.

cyprus106

Programmer
Apr 30, 2001
654
I need a way to read the entire contents of a designated directory. I need to access a list of files programatically. This isn't for the user directly, so I'm not trying to show them in a directory or dialog or anything.

Basically, I've got a random number generator. It picks a random number and I've got a few different files in a directory. Whatever number is picked, it will open the corresponding file. Since the files may vary, I need to have a non hard-coded method of doing this.
On that same note, how do I read how many files are in a directory?

Thanks a lot... Cyprus
 
To list the files in a dir, the following should work (untested):

ffblk ffblk;
list<string> files;

int result=findfirst(&quot;C:\\designatedFolder\\*.*&quot;,&ffblk,FA_ARCH);
while(result){
string tempstr=ffblk.ff_name;
files.push_back(tempstr);
result=findnext(&ffblk);
}

//output number of files
cout<<&quot;There are &quot;<<files.size()<<&quot; files in folder.\n\n&quot;;

//show list of files
cout<<&quot;Files in folder:\n&quot;;
list<string>::iterator iter=files.begin();
while(iter!=files.end()){
string& tempstr=*iter;
cout<<&quot;\t&quot;<<tempstr.c_str()<<endl;
iter++;
}

Or if I've missed the point, lemme know & I'll see if I can rethink.
Cheers,
Douglas JL Common sense is what tells you the world is flat.
 
Sorry - the first while loop in the above code should have the following condition:
while(!result)

or

while(result==0)

Problem with being sloppy is you screw up. Common sense is what tells you the world is flat.
 
As a quick but dirty solution you could hide a filelist box on the form and read the list from there.
Its easy to change the directory of the list box.

char *dir1 = new char [500];
char *buffer1 = new char [500];

strcpy (dir1, &quot;C\\windows\\temp&quot;);

FForm1->FileListBox3->Directory = dir1;
FForm1->FileListBox3->Mask = &quot;*.*&quot;;

int x = FForm1->FileListBox3->Items->Count;

for (int y = 0; y < x; y++)
{
// Adding this line puts the directory path at the
// beginning of the char string.
strcpy (buffer1, dir1);

// I add this to the string because the way I get
//the directory path does not include it.
strcat (buffer1, &quot;\\&quot;);

// This is the file name I get from the filelistbox.
strcat (buffer1, FForm1->FileListBox3->Items-
>Strings[y].c_str ());
}
delete dir1;
delete buffer1;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top