To check if a file exists in Rust, we can use the std::fs::metadata()
function. This function returns a Result
object which can be used to determine if the file exists or not. Here's an example:
main.rs201 chars11 lines
In this example, we first define the file_path
variable which contains the path to the file we want to check. We then call fs::metadata()
with that path, which returns a Result
object.
If fs::metadata()
returns an Ok
variant, that means the file exists. We print "File exists!" in that case. If fs::metadata()
returns an Err
variant, that means the file does not exist. We print "File not found!" in that case.
We could also use the .is_ok()
method to simplify the code:
main.rs200 chars12 lines
Finally, it's worth noting that the metadata()
function returns more information than just whether the file exists, so if we need more information about the file itself we can use this function's return value to extract it.
gistlibby LogSnag