I need to write to file descriptor 3. I have been searching for it but the documentation is quite poor. The only thing that I have found is the use of libc
library and the fdopen
method, but I haven't found any example about how to use it or write on it.
Can anyone provide me an example of writing to a file descriptor in Rust?
In addition to reading and writing to console, Rust allows reading and writing to files. The File struct represents a file. It allows a program to perform read-write operations on a file. All methods in the File struct return a variant of the io::Result enumeration. The commonly used methods of the File struct are listed in the table below −
Rust - File Input/ Output. In addition to reading and writing to console, Rust allows reading and writing to files. The File struct represents a file. It allows a program to perform read-write operations on a file. All methods in the File struct return a variant of the io::Result enumeration.
One-line functions are available for reading and writing files in Rust 1.26 and onwards. The std::fs module includes basic techniques for manipulating the contents of the local file system. The read_to_string () function opens files with fewer imports excluding intermediate variables.
One-line functions are available for reading and writing files in Rust 1.26 and onwards. The std::fs module includes basic techniques for manipulating the contents of the local file system.
You can use FromRawFd
to create a File
from a specific file descriptor, but only on UNIX-like operating systems:
use std::{
fs::File,
io::{self, Write},
os::unix::io::FromRawFd,
};
fn main() -> io::Result<()> {
let mut f = unsafe { File::from_raw_fd(3) };
write!(&mut f, "Hello, world!")?;
Ok(())
}
$ target/debug/example 3> /tmp/output
$ cat /tmp/output
Hello, world!
from_raw_fd
is unsafe because there's no guarantee that the file descriptor is valid or who is actually responsible for that file descriptor.
The created File
will assume ownership of the file descriptor: when the File
goes out of scope, the file descriptor will be closed. You can avoid this by using either IntoRawFd
or mem::forget
.
See also:
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