Dear Masters.
I want to find out if there is a way to check if the file with certain name exists before i open or create it.
Another thing is :
Is there an option to open file in binary mode (as ios::binary in C++)
The modules you need are path and fs:
std::path::Path::new("path/to/file").exists()
Rust doesn't have a concept of text-mode reading, so you always get binary mode.
https://doc.rust-lang.org/book/second-edition/ch12-02-reading-a-file.html
Thanks. Im into it.
Thanks, it was really handy.
Another thing i was wondering of was how do i read the file line by line until the EOF was met like in C++ for example.
Here's the code for lines: https://rust-lang-nursery.github.io/rust-cookbook/basics.html#ex-std-read-lines
Wow, thanks.
And the last question for today:
Can you tell me analogs of _chdir() in C++
And how to remove existing files.
This is usually not a good idea, because of race conditions.
Just open the file without checking and use the error values to determine if the file already existed. That way, there's no possibility that the file is accidentally moved/deleted/created between checking and opening the file.
Thanks, it was handy. Trying to find some info about Navigation through file system and erasing existing files.
HOORAY, Ive found how to erase existing files.
Its the fs::remove_file().
Now i only need to know how to navigate through the file system.
You can use this walkdir crate for that GitHub - BurntSushi/walkdir: Rust library for walking directories recursively.
Thank you Sir.
But it is quite complicated.
Is there some easier way like in C++ for example:
_chdir("Path");
_chdir(..) up one level.
Thanks.
here is an example from the article:
fn dump_dir(dir: &str) -> io::Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let data = entry.metadata()?;
let path = entry.path();
if data.is_file() {
if let Some(ex) = path.extension() {
if ex == "rs" && data.len() > 1024 {
println!("{} length {}", path.display(),data.len());
}
}
}
}
Ok(())
}
and i am trying it in my project as following:
use std::fs;
use std::env;
......
for dirname in fs::read_dir(env::current_dir())?{
println!("{}",dirname?.path().display());
}
......
and i get mistakes that i dont realize how to fix:
for dirname in fs::read_dir(env::current_dir())?{
| ^^^^^^^^^^^^ the trait std::convert::AsRef<std::path::Path>
is not implemented for std::result::Result<std::path::PathBuf, std::io::Error>
|
error[E0277]: the ?
operator can only be used in a function that returns Result
(or another type that implements std::ops::Try
)
--> src\main.rs:32:20
|
32 | for dirname in fs::read_dir(env::current_dir())?{
| ---------------------------------
| |
| cannot use the ?
operator in a function that returns ()
| in this macro invocation