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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.

You Might Also Like