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");
3

1 Answer

I fixed my problem with following code:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest