list problem
Jun 3, 2010 at 5:26pm UTC
I use one list<string> object to store the file names in one directory. There is a function called ScanDiretory(list) which adds file names into the list. In the end of this function, I check list.size(), nothing was wrong. But just after the function finished, I rechecked the size, it return 0.
Here is the codes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
bool ScanDirectory(string _dirname,string _fnmp, list<string> _lname)
{
DIR *dir;
struct dirent *ent;
size_t found;
string fn,ext;
dir = opendir (_dirname.c_str());
if (dir != NULL)
{
cout<<"Open directory <" <<_dirname<<"> successfully!" <<endl;
while ((ent = readdir (dir)) != NULL)
{
// printf ("%s\n", ent->d_name);
string tmp;
tmp = ent->d_name;
found = tmp.find_last_of("." );
if (found!=tmp.npos)
{
fn = tmp.substr(0,found);
ext = tmp.substr(found+1);
if (fn==_fnmp)
{
_lname.push_back(tmp); //add to the list
// printf ("%s %s\n",fn.c_str(),ext.c_str());
}
}
}
_lname.sort();
cout<<"Scan directory <" <<_dirname<<"> finished!" <<endl;
cout<<(int )_lname.size()<<" mean path files were found." <<endl;
for (list<string>::iterator it=_lname.begin();it!=_lname.end();it++)
cout<<*it<<endl;
// cout<<(int)_lname.size()<<" mean path files were found."<<endl;
closedir(dir);
return true ;
}
else
{
cout<<"Can not open directory <" <<_dirname<<">" <<endl;
return false ;
}
}
Jun 3, 2010 at 6:16pm UTC
You aren't returning the list to the caller.
Jun 3, 2010 at 8:27pm UTC
Can you explain more in details? I'm not quite sure what you mean.
Jun 3, 2010 at 10:39pm UTC
This function signature...
1 2 3 4
bool ScanDirectory(string _dirname,string _fnmp, list<string> _lname)
{
// ...
}
... passes a
copy of your list _lname into the function. That
copy is destroyed when your function exits.
In order to change the
original list that you pass in you need to pass it by reference rather than a copy.
1 2 3 4
bool ScanDirectory(string _dirname,string _fnmp, list<string>& _lname)
{
// ...
}
That way when the function adds elements to _lname it is adding them to the one you passed in rather than a copy.
Last edited on Jun 3, 2010 at 10:40pm UTC
Jun 4, 2010 at 9:30am UTC
Thanks. Got it.
Topic archived. No new replies allowed.