0

I'm writing a code to read all the files inside the subdirectory "resultsNEW" located in my main directory, store their names in a vector and use them for other stuff I'm using opendir and readdir to read the names of the files, and of course it's including "." and ".."...now, the problem is I'm trying to eliminate them, but for some reason I cannot do that. Here's my code

int RFiles(vector<string>& f)
{
    //path of the directory containing the files
    string path = "./resultsNEW";

    DIR* dir;
    dirent* file;

    dir = opendir(path.c_str());
    if (dir)
    {
        while (file = readdir(dir))
        {
            if (file->d_name == "." || file->d_name == "..") // HERE IS THE PART WHICH IS NOT WORKING
            {
                cout << "File not good!" << endl;
            }
            else
            {
                cout << "Reading file:" << file->d_name << endl;
                string temp = path + "/" + file->d_name;
                f.push_back(temp);
            }
        }
        return(0);
    }
    else
    {
        return(1);
    }
    closedir(dir);
}

I added the condition

if (file->d_name=="." || file->d_name=="..")

to eliminate . and .., but they're included nevertheless...the output is

Reading file:Output_M 0.1000E+12_nu  3.00_tau0.400_Reff0.3000E+04.txt
Reading file:Output_M 0.1000E+13_nu 22.00_tau0.200_Reff 0.1000E+05.txt
Reading file:Output_M 0.1000E+11_nu  1.00_tau0.500_Reff 0.1000E+04.txt
Reading file:..
Reading file:.

I'm sure there's something obvious I'm missing here, but really cannot figure out what...

Julian Declercq
  • 1,536
  • 3
  • 17
  • 32
Carlo
  • 1,321
  • 12
  • 37
  • You can't compare c-strings with `==`. Use `strcmp`. – Karsten Koop Dec 02 '16 at 12:36
  • Ok, I followed @Karsten 's suggestion, and now it works! I'm really surprised, I was sure the == operator could be used for that, many people suggested using it for similar issues... – Carlo Dec 02 '16 at 13:32
  • No, the == operator compares the addresses of the pointers, not the string content. See also [this question](http://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c). If you are using `std::string`, it's a different story, but `dirent` is a c struct. – Karsten Koop Dec 02 '16 at 13:38

0 Answers0