2

I have written a function which accepts DIR * as argument and lists files inside that (with readdir function)

In addition, I just want to be able to stat files returned by readdir. It is not clear where DIR * is pointing to, so is there a way to get full path of directory from DIR * or is there any other way that I can stat files with?

3 Answers 3

4

You can use dirfd(), as many other answers, and then for each entry read with readdir() call function fstatat():

int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags); 

I think this relatively obscure function does just what you need.

Alternatively you could call openat() passing in the fd of the directory and the pathname read from the directory. Then do a fstat() to get the file stats.

Sign up to request clarification or add additional context in comments.

Comments

2

I don't think so, but you should be able to use dirfd() to get the file descriptor corresponding to the DIR *, and using that you can call fchdir() to change into that directory.

Then the names returned by readdir() become local to your current dir, and you can just stat() them directly.

UPDATE: Just to clarify, this is not the same thing as calling chroot(), it's just an ordinary change of the process' current directory.

3 Comments

Nice workaround, but is there no way without chdir? UPDATE: chdir I meant instead of chroot!
Just out of curiousity, if after calling fchdir() he calls getcwd(), would he get the real name of the directory?
@rodrigo: Yes, it returns the path where DIR * is pointing to!
1

Based on @unwind answer, and since you are in linux:

  • Call dirfd() to get the file descriptor of the directory
  • Get your pid using getpid()
  • Read the link /proc/<pid>/fd/<dirfd> using readlink(). It will refer to your directory by name!

2 Comments

Nice way, it seems better than fchdir! But these answers mean that there is no straight way of doing it, right?
@PLuS. Right. Generally speaking, you cannot go from a file-descriptor to a file-name. That's by design of the unix file system: file-name -> dir-entry -> inode <- open-file-description <- file-descriptor (well, maybe not too exact, but you get the idea...). The /proc readlink method is just a linux hack to get to this information, which may be accurate.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.