Reputation: 53
Very new to Rust and am looking for clarification about rust file paths that are outside the project directory. I would expect reading a .txt file from say the desktop to look something roughly like this:
fs::read_to_string("./Desktop/test.txt");
However, this does not seem to work. Is this an issue with the file path listed or does Rust only allow access to files in the project directory? If this is the default case how does one allow access to files elsewhere in the system outside the current working directory? Say the project is in Documents and we want to access some text file on the Desktop.
Found the answer, seems the path that I am looking for is like this :
fs::read_to_string("/Desktop/test.txt");
Seems the "." was looking in the current directory.
Upvotes: 4
Views: 7292
Reputation: 168988
As specified, the path will be relative to the working directory of the process. If the working directory isn't your home directory, then you need to be more specific about where the file is.
Note that the working directory can change depending on how you run the program. The link above has more information on this topic.
You can obtain your user's desktop directory using desktop_dir
from the dirs
crate, which will make the working directory irrelevant in this particular case. It will also correctly determine the user's desktop directory on many different operating systems.
fs::read_to_string({
let mut path = dirs::desktop_dir().expect("no desktop directory");
path.push("test.txt");
path
})
Upvotes: 1
Reputation: 30577
When you open a path that starts with ./
, it is relative to the current working directory.
Assuming that the program does not change the working directory itself, that would be whatever directory the user was in when they started the executable.
Note that it is not necessarily the project directory: when you are developing your program, you will probably run it via cargo run
, but when it is ready you would most likely copy the target executable into a directory that is in the path. The working directory can be completely different to the directory in which the executable is placed.
Your program can find out the current working directory by calling std::env::current_dir
If you want a path that does not depend on the working directory, you can use an absolute path, ie. starting with /
.
Rust is no different to any other programming language in this respect. In particular, files are not opened in respect to the project dir.
Upvotes: 8