FlensT
FlensT

Reputation: 21

Rust - writeln! doesn't write to file

The reader() method works, and the data from the file is loaded, but the writer() does not work, and there is no error, it simply does not write silently. But when I open the file manually (without using the CookieStoreFS structure) and create a BufWriter, everything works fine.

I have following code:

use std::{path::PathBuf, env::current_dir, fs::File, error::Error, io::{BufReader, BufWriter}};


//TODO ERROR IF COOKIE FILE NOT EXISTS
pub struct CookieStoreFS{
    path: PathBuf,
}

impl Default for CookieStoreFS {
    fn default() -> Self {
        let mut default_path = current_dir().unwrap();
        default_path.push("cookie.json");
        Self { path: default_path }
    }
}

impl CookieStoreFS{
    pub fn new(path: PathBuf) -> Self{
        Self{
            path
        }
    }

    fn create(&self) -> Result<File, Box<dyn Error>>{
        match File::create(&self.path){
            Ok(f) => Ok(f),
            Err(err) => Err(err.into())
        }
    }

    fn open(&self) -> Result<File, Box<dyn Error>>{
        if !self.path.exists(){
            return self.create()
        }
        return match File::open(&self.path){
            Ok(f) => Ok(f),
            Err(err) => Err(err.into())
        }
    }

    pub fn reader(&self) -> Result<BufReader<File>, Box<dyn Error>>{
        let file = self.open()?;
        Ok(BufReader::new(file))
    }

    pub fn writer(&self) -> Result<BufWriter<File>, Box<dyn Error>>{
        let file = self.open()?;
        Ok(BufWriter::new(file))
    }
}

and it doesn't write to the file without any errors:

let mut writer = COOKIE_STORE_FS.writer().unwrap();
writeln!(writer, "asdasd");
writeln!(&mut writer, "asdasd");

Upvotes: 0

Views: 1364

Answers (1)

FlensT
FlensT

Reputation: 21

I fixed my problem with following code:

File::options().read(true).write(true).open(&self.path)

Upvotes: 2

Related Questions