Retrieving file/directory name from stdin

I'm working on a command line application that accepts input via stdin redirection.
I want to add a feature that checks if the provided input is a directory. For example, if a directory is passed via redirection, it should be able to detect it.

For example,

$ ./app < d
d is a directory
$./app < f
f is not a directory

How can I check if the input is a directory? are there any libraries?

There is ::std::path::Path::is_dir.

Yeah, I'm aware of that.

The problem is: How do I retrieve the redirected file/directory name/path?

::std::fs::metadata traverses symbolic links and ::std::fs::Metadata also has an is_dir method.

You can use the fstat libc function on stdin fd to get various information on whatever is backing stdin, including the file type.

1 Like

No need to use libc, the standard library abstracts that. I'd write something like this:

let fd = stdin().as_fd().try_clone_to_owned().unwrap();
let file = File::from(fd);
let meta = file.metadata().unwrap();
dbg!(meta.is_dir());
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.