English 中文(简体)
Rust - File Input/ Output
  • 时间:2024-12-22

Rust - File Input/ Output


Previous Page Next Page  

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 psted in the table below −

Sr.No Module Method Signature Description
1 std::fs::File open() pub fn open<P: AsRef>(path: P) -> Result The open static method can be used to open a file in read-only mode.
2 std::fs::File create() pub fn create<P: AsRef>(path: P) -> Result Static method opens a file in write-only mode. If the file already existed, the old content is destroyed. Otherwise, a new file is created.
3 std::fs::remove_file remove_file() pub fn remove_file<P: AsRef>(path: P) -> Result<()> Removes a file from the filesystem. There is no guarantee that the file is immediately deleted.
4 std::fs::OpenOptions append() pub fn append(&mut self, append: bool) -> &mut OpenOptions Sets the option for the append mode of file.
5 std::io::Writes write_all() fn write_all(&mut self, buf: &[u8]) -> Result<()> Attempts to write an entire buffer into this write.
6 std::io::Read read_to_string() fn read_to_string(&mut self, buf: &mut String) -> Result Reads all bytes until EOF in this source, appending them to buf.

Write to a File

Let us see an example to understand how to write a file.

The following program creates a file data.txt . The create() method is used to create a file. The method returns a file handle if the file is created successfully. The last pne write_all function will write bytes in newly created file. If any of the operations fail, the expect() function returns an error message.

use std::io::Write;
fn main() {
   let mut file = std::fs::File::create("data.txt").expect("create failed");
   file.write_all("Hello World".as_bytes()).expect("write failed");
   file.write_all("
TutorialsPoint".as_bytes()).expect("write failed");
   println!("data written to file" );
}

Output

data written to file

Read from a File

The following program reads the contents in a file data.txt and prints it to the console. The "open" function is used to open an existing file. An absolute or relative path to the file is passed to the open() function as a parameter. The open() function throws an exception if the file does not exist, or if it is not accessible for whatever reason. If it succeeds, a file handle to such file is assigned to the "file" variable.

The "read_to_string" function of the "file" handle is used to read contents of that file into a string variable.

use std::io::Read;

fn main(){
   let mut file = std::fs::File::open("data.txt").unwrap();
   let mut contents = String::new();
   file.read_to_string(&mut contents).unwrap();
   print!("{}", contents);
}

Output

Hello World
TutorialsPoint

Delete a file

The following example uses the remove_file() function to delete a file. The expect() function returns a custom message in case an error occurs.

use std::fs;
fn main() {
   fs::remove_file("data.txt").expect("could not remove file");
   println!("file is removed");
}

Output

file is removed

Append data to a file

The append() function writes data to the end of the file. This is shown in the example given below −

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
   let mut file = OpenOptions::new().append(true).open("data.txt").expect(
      "cannot open file");
   file.write_all("Hello World".as_bytes()).expect("write failed");
   file.write_all("
TutorialsPoint".as_bytes()).expect("write failed");
   println!("file append success");
}

Output

file append success

Copy a file

The following example copies the contents in a file to a new file.

use std::io::Read;
use std::io::Write;

fn main() {
   let mut command_pne: std::env::Args = std::env::args();
   command_pne.next().unwrap();
   // skip the executable file name
   // accept the source file
   let source = command_pne.next().unwrap();
   // accept the destination file
   let destination = command_pne.next().unwrap();
   let mut file_in = std::fs::File::open(source).unwrap();
   let mut file_out = std::fs::File::create(destination).unwrap();
   let mut buffer = [0u8; 4096];
   loop {
      let nbytes = file_in.read(&mut buffer).unwrap();
      file_out.write(&buffer[..nbytes]).unwrap();
      if nbytes < buffer.len() { break; }
   }
}

Execute the above program as main.exe data.txt datacopy.txt. Two command pne arguments are passed while executing the file −

    the path to the source file

    the destination file

Advertisements