readdir() ignore . and ..

Hi i have the following function that reads every subdir of a directory:
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
bool doDir(std::string dir)
{
  dirent* pDirent;
  DIR *pDir;

  pDir = opendir(dir.c_str());

  if(!pDir)
  {
    std::cout << "cannot open dir: " << dir.c_str() << '\n';
    return false;
  }

  while((pDirent = readdir(pDir)))
  {
    if(pDirent->d_type == DT_DIR)
        std::cout << dir.c_str() << pDirent->d_name << '\n';
  }



  closedir(pDir);

  return true;

}


I would like to call this function recursively by calling doDir(pDirent->d_name) to find every subdir of the subdirs.

The problem is that the readdir function also returns the "." and ".." directories so i cant.

How do i go about ignoring / removing them?

I tried simply checking the names like so:
1
2
if(pDirent->d_name == "..")
  ..


but if i do that then the compiler gives me a warning about "warning: comparison with string literal results in unspecified behaviour [-Waddress]"
if(pDirent->d_name == "..")
That's just plain wrong. It looks like you want to compare two C-strings (i.e. check if the characters in each C-string are the same or not), but you're actually comparing pointers.

If you have C-strings to compare, which these are (well, a char array and a "string literal" - char pointer to a const array of char), use a function that's made for it.

Like strcmp, for example.

Last edited on
ohhh, of course!
thank you

i think i thought d_type was of type string or something
thanks
Topic archived. No new replies allowed.