I found Ancient Dragon's code snippet for reading the files in a folder. I modified it a little because I want it to display what those files are. The problem is, it also displays the two parent directories, '.' and '..'. I was wondering if there was a way to skip over those when it's reading the files in. Here is the code for the function that I am using:

typedef vector<string> LIST;
int seekdir(vector<LIST>& mylist,vector<string> &file, string path)
{

    DIR* dir = opendir(path.c_str());
    vector<string> lst;
    struct dirent *d;
    
    if(dir == 0)
    {
        cout << "Can not open directory '" << path << "'\n";
        return 1;
    }
//    cout << "directory '" << path << "' opened ok\n";
    
    while( (d = readdir(dir)) != NULL)
    {
        if( d->d_type == DT_DIR && strcmp(d->d_name,".") != 0 &&
            strcmp(d->d_name,"..") != 0)
        {
            string p = path + "/" + d->d_name;
            seekdir(mylist,file,p);    

            lst.push_back(string(d->d_name));
        }
        else if(d->d_type == DT_REG)
        {
            lst.push_back(string(d->d_name));
        }
        file.push_back(string(d->d_name));
    }

If you look at his original code it's not much different, I just added an argument to the function and have it push back the name of the file that it is at. This is the main function that reads out the file to the terminal:

for (unsigned int i = 0; i < files.size();i++)
    {    
        cout << files[i] << endl;
    }

The code I have works at this point but I need to ignore the parent directories in the printout for something I am going to do after I solve this problem. If anyone can help it would be greatly appreciated.

Recommended Answers

All 3 Replies

>> it also displays the two parent directories, '.' and '..'.

Line #30 stores both "." and ".." in addition to the directory and file names, so you have to work around that.

Move line30 up to line 29 so that it's within the else statement.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.