How i can write to file


#1

how do i write an entry to the file and not to the console

fn dfs(field: &mut [[bool; FIELD_SIZE]; FIELD_SIZE], start: (usize, usize), finish: (usize, usize)) -> bool {
if field[start.0][start.1] {
    return false;
}

field[start.0][start.1] = true;

if start == finish {
    let out_pos = get_chess_coords(start);
    println!("{}{}", out_pos.0, out_pos.1);
    return true;
}

for delta in DELTAS.iter() {
    let new_pos = ((start.0 as i32 + delta.0) as usize, (start.1 as i32 + delta.1) as usize);
    if dfs(field, new_pos, finish) {
        let out_pos = get_chess_coords(start);
        println!("{}{}", out_pos.0, out_pos.1);
        return true;
    }
}

return false;

}


#2

Take a look at std::fs::File and also std::io::BufWriter.

Create a File object, wrap it in BufWriter, and then call write_fmt method instead of println!.


#3

Also, have a look at https://doc.rust-lang.org/stable/rust-by-example/std_misc/file.html.


#4

data is overwritten


#5

if you don’t want that, have a look at OpenOptions::append()
https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#examples-4


#6

How it work? I don’t understand


#7

What is it you do not understand? The link gives you an explicit example how to open a file in append mode.


#8
use std::fs::OpenOptions;
use std::io::prelude::*;

fn main() {
    let mut file = OpenOptions::new().append(true).create(true).open("foo.txt").unwrap();
    write!(&mut file, "Hello, world!");
}

#9

thanks, I had a mistake because of the fact that I wrote file.write.
now everything turned out :blush: