0
votes

If given a directory path in the form of a std::string, how can I get a dirent struct pointing to that directory?

I could start by getting a DIR* to the needed directory using opendir(). Then I could use readdir() on my DIR*, but that tries to return entries within the DIR*, not the DIR* itself.

So what is the appropriate way to achieve this?

2
Why do you need a struct dirent?Mat
You could probably use stat() to get the information you want.clstrfsck

2 Answers

2
votes

If you want the directory entry for the directory itself within its parent, do this:

  1. stat(path). Record st_dev and st_ino.
  2. stat(path + "/.."). If this st_dev is not equal to the st_dev you got for path, path is a mount point, and the rest of what I'm about to say will not work.
  3. opendir(path + "/..") gives you a DIR* for the parent directory.
  4. readdir on that until you find a dirent with d_ino equal to the st_ino you saved in step 1. That's the dirent you want.

The only piece of information you get from this algorithm that you can't get from just doing step 1, though, is the name of the directory within its parent directory. And there's a much easier way to get that information: call realpath() to canonicalize the path, then extract the last component of the result. No problems with mount points or symlinks, either.

1
votes

Repeat readdir() until you reach the dirent named ., which is the directory itself. To see this from the shell, type ls -al.