OS Error 5 when Writing to file on windows 10

I am unable to write to files using the rust standard library (through std::io::Write::write_all). It seems that no matter what I do I get this error.

Error: Os { code: 5, kind: PermissionDenied, message: "Access is denied." }

A few things I have tried to solve this issue.
Reinstall all rust components
Reinstall rust analyzer
Change toolchain to gnu-stable then msvc-stable
Change the OpenOptions for opening the file
Run with administer permissions through Powershell
Restart my PC (Several times)

Has anybody else had this problem? If so do you have a potential fix?
Thanks in advance.

Try showing your code.

This is just example code but I got the same result nethertheless.

use std::io::Write;

fn main() {
    let mut file = std::fs::File::open("thing.txt").unwrap();
    file.write_all(b"PLACEHOLDER").expect("Something went wrong opening the file");
}

Result:

thread 'main' panicked at 'Something went wrong opening the file: Os { code: 5, kind: PermissionDenied, message: "Access is denied." }'

File::open opens a file in read-only mode. You need to open it with write access:

let mut file = OpenOptions::new().write(true).open("thing.txt").unwrap();
file.write_all(b"PLACEHOLDER").expect("Something went wrong opening the file");
4 Likes

Thank you! My code works now.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.