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:
stat(path)
. Recordst_dev
andst_ino
.stat(path + "/..")
. If thisst_dev
is not equal to thest_dev
you got forpath
,path
is a mount point, and the rest of what I'm about to say will not work.opendir(path + "/..")
gives you aDIR*
for the parent directory.readdir
on that until you find adirent
withd_ino
equal to thest_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
.
精彩评论