I am trying to read and write files passing around a File
object. It keeps giving me errors saying the file descriptor is not valid.
Does this have something to do with how Rust works in memory? Like if do below it does not work, saying write_all
method not found in file. I also tried declaring it as std::fs::File
but not working.
What's the way around this? I could just pass the filename but opening and closing the file constantly seems weird.
fn write_to_file(fd: File, data: &str){
fd.write_all(data.as_bytes()).expect("error writing");
}
fn main(){
let filename = "testing.txt";
let mut fd = File::create(filename).expect("error creating file");
write_to_file(fd,"text to write");
}
CodePudding user response:
If you want to use the File::write_all()
function of std::fs::File
you will need the std::io::Write
trait in scope (in the docs you will also see
use std::io::prelude::*;
). Apart from that the file must be mutable if you want to alter its content.
I guess this is what you want:
use std::fs::File;
use std::io::Write;
fn write_to_file(fd: &mut File, data: &str){
fd.write_all(data.as_bytes()).expect("error writing");
}
fn main(){
let filename = "testing.txt";
let mut fd = File::create(filename).expect("error creating file");
write_to_file(&mut fd, "text to write");
}
And the link to the Playground.
CodePudding user response:
You're trying to use fd
in two functions, but your code tells Rust to specifically forbid that, and limit fd
's existence to one function at a time.
Rust has a concept of single ownership, which is the default for non-copyable types like File
.
When you have a function argument fd: File
, this means the function will take over the exclusive ownership the fd
.
fd: &File
takes a temporary shared reference. It allows the same object to be accessed from multiple places.
fd: &mut File
takes a temporary exclusive reference. It's a similar exclusivity guarantee to passing ownership, except that when scope of &mut
ends, the ownership is automatically returned to the previous owner, instead of destroying the object.
So you need to pass a temporary reference to write_to_file
(with fd: &mut File
), instead of giving it fd
forever (fd: File
).