PLuS
PLuS

Reputation: 642

stat file from DIR *

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?

Upvotes: 2

Views: 679

Answers (3)

rodrigo
rodrigo

Reputation: 98358

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.

Upvotes: 4

rodrigo
rodrigo

Reputation: 98358

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!

Upvotes: 1

unwind
unwind

Reputation: 399823

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.

Upvotes: 2

Related Questions