开发者

How can I get a dirent struct from a string path?

If given a directory path in the开发者_JAVA百科 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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜