Working with files


#1

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.


#2

Another thing is :


#3

Is there an option to open file in binary mode (as ios::binary in C++)


#4

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


#5

Thanks. Im into it.


#6

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.


#7

Here’s the code for lines: https://rust-lang-nursery.github.io/rust-cookbook/basics.html#ex-std-read-lines


#8

Wow, thanks.


#9

And the last question for today:
Can you tell me analogs of _chdir() in C++
And how to remove existing files.


#10

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.


#11

Thanks, it was handy. Trying to find some info about Navigation through file system and erasing existing files.


#12

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.


#13

You can use this walkdir crate for that https://github.com/BurntSushi/walkdir


#14

Thank you Sir.
But it is quite complicated.
Is there some easier way like in C++ for example:
_chdir(“Path”);
_chdir(…) up one level.


#15

https://doc.rust-lang.org/std/env/fn.set_current_dir.html


#16

Thanks.


#17

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