Ignoring the fact that I'm using unwrap
to ignore what happens if the file doesn't exist, it seems to me like this short bit of code should work (as long as the file does exist):
use std::fs::File;
use std::io::Write;
fn main() {
let mut f = File::open("test.txt").unwrap();
let result = f.write_all(b"some data");
match result {
Ok(_) => println!("Data written successfully"),
Err(e) => panic!("Failed to write data: {}", {e}),
}
}
Instead, I'm getting this:
thread 'main' panicked at 'Failed to write data: Bad file descriptor (os error 9)', src/main.rs:10:19
To be clear, I know if I follow one of the many examples online, I can write to a file. The question isn't "how do I write to a file?". It's why THIS isn't working.
It isn't working because File::open()
open's a file in read-only mode. Instead you have to use File::create()
which opens a file in write-only mode. Alternatively you can also use OpenOptions
, to further specify if you want to append()
to a file instead.
use std::fs::File;
use std::io::Write;
fn main() {
let mut f = File::create("test.txt").unwrap();
let result = f.write_all(b"some data");
match result {
Ok(_) => println!("Data written successfully"),
Err(err) => panic!("Failed to write data: {}", err),
}
}
Using File::create()
is the same as using OpenOptions
in the following way:
use std::fs::OpenOptions;
use std::io::Write;
fn main() {
let mut f = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open("test.txt")
.unwrap();
let result = f.write_all(b"some data");
match result {
Ok(_) => println!("Data written successfully"),
Err(err) => panic!("Failed to write data: {}", err),
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With