How do I determine the current directory that I am in?

Hi, so I am using this crate called fs_extra to do stuff like copy and paste files.

I wanted to know if there is a way to determine the current directory that I am in using this crate or outside of this crate?

1 Like

Is this part of the Rust programming language?

Please follow the link. It says exactly where this function is coming from, and you'd have to read the documentation anyway, if you want to use it.


fn main() -> std::io::Result<()>
    let dir = env::current_dir()?;
    println!("{}", dir.display());

So just one question, why do I need to return something in main function -> std::io::Result<()> in order to run the first line let dir = env::current_dir()?;? Otherwise I get an error.

Because that's how the question mark operator works. If you don't want to return a result, you need to handle the error in some other way, e.g. by matching or calling unwrap.

So how come come it forces me to handle any possible errors?

That's just Rust's design — it wants to push programmers towards handling all errors, because silently ignored errors are often a source of bugs in programs.

For example, it is possible that a program doesn't have a valid current directory. The dir may have been deleted after the program set it as its current dir. Your program needs to handle such case, instead of e.g. crashing during dir.display() or printing garbage.

If ? doesn't fit what you do, there's also .unwrap() and .unwrap_or(some_alternative_value) and match, and a few more.


That is a good thing, but like in regards to that function, how did they like force the programmer to have an error handler (or whatever it is callled)?

So with unwrap, if soemthing went wrong it panics and has a default message otherwise it passes through?

Rust's Result type is responsible for enforcing error handling. Values wrapped in Result can't be accessed until you decide how to handle the error case.

Yes .unwrap() panics. It's not great for use in real programs, because any error may stop the whole program, but it's fine for quick hacks and cases where you're 99.999% sure the error won't happen anyway.

? stops execution of only the function it's in, rather than the whole program. Of course in case of main there's no practical difference, but typically programs have more than just main.

1 Like

I see thanks mate and it makes more sense now :slight_smile:

But like with this particular function env::current_dir()

How did the developers ensure the programmer has an error handler for this really?

current_dir ensures this by returning Result<PathBuf, io::Error> instead of just PathBuf, which means you can't access the PathBuf directly.

1 Like

Ah right makes more sense, thanks

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.