Question

I was given this code a while back. I finally got around to testing it (with some changes to put the files in a different place)...

void AddFiles(AnsiString path/*, TDataSet *DataSet*/)
{
TSearchRec sr;
int f;
    f = FindFirst(path+"\\*.*", faAnyFile, sr);
    while( !f )
    {
        if(sr.Attr & faDirectory)
        {
                if(sr.Name != "."   &&   sr.Name != "..")
                {
                        path.sprintf("%s%s%s", path, "\\", sr.Name);
                        AddFiles(path/*, DataSet*/);
                }
        }
        else
        {
                Form1->ListBox1->Items->Add(path+ "\\"+ sr.Name);
                //DataSet->Append();
                //DataSet->FieldByName("Name")->Value = sr.Name;
                /* other fields ... */
                //DataSet->Post();
        }
        f = FindNext(sr);
    }
    FindClose(sr);
}

It doesn't work properly. In the beginning it gets mixed up..

a real structure of...

root root\subdir1 root\subdir2 root\subdir3

gets messed up like this...

root root\subdir1 root\subdir1\subdir2 root\subdir1\subdir2\subdir3

and eventually it stops including the root or sub\sub folders and 'path' just contains a subfolder (without its root folders)

this is completely useless for aquring useable full-path filenames.

so either can you tell me where the code is going wrong... or give me some advice on how to get the full path filenames in a dir and all its subdirs.

I want it to be as basic as possible. i.e. no uncommon advanced c++ features. stuff that a builder noob is likely to be able to debug.

Was it helpful?

Solution

Here you append each subpath to the current path:

path.sprintf("%s%s%s", path, "\\", sr.Name);
AddFiles(path/*, DataSet*/);

Use a new variable for the combined path, so you don't mess up the path variable you still need for the rest of the files/dirs in the directory:

AnsiString subpath;
subpath.sprintf("%s%s%s", path, "\\", sr.Name);
AddFiles(subpath/*, DataSet*/);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top