Methods for File I/O

Given below are some methods and their syntax for various file I/O operations:

Method

Module

Syntax

Description

fs::write()

std::fs

fs::write(“filepath”, “content”)?;

Write a slice as the entire contents of a file.

fs::read()

std::fs

let variable_name = fs::read(“filepath”);

Read the entire contents of a file into a bytes vector.

fs::read_to_string()

std::fs

let variable_name = fs::read_to_string(“filepath”);

Read the entire contents of a file into a string.

File::create()

std::fs::File

let mut variable_file_name = File::create(“filepath”)?;

Creates a new file and write bytes to it (you can also use write())

write_all()

std::io::Write

variable_file_name.write_all(content.as_bytes())?;

Attempts to write an entire buffer into this writer.

File::open()

std::fs::FIle

let mut variable_file_name = File::open(“filepath”)?;

Attempts to open a file in read-only mode.

read_to_string()

std::io::Read

variable_file_name. read_to_stfing(&mut buffer)?;

Read all bytes from a reader into a new String. the content will be copied to buffer variable.

remove_file()

std::fs

fs::remove_file(“filepath”)?;

Removes a file from the filesystem.

copy()

std::fs

fs::copy(“original_filepath”, “destination_filepath”)?;

Copies the contents of one file to another. This function will also copy the permission bits of the original file to the destination file.

File I/O in Rust

File I/O in Rust enables us to read from and write to files on our computer. To write or read or write in a file, we need to import modules (like libraries in C++) that hold the necessary functions. This article focuses on discussing File I/O in Rust.

Similar Reads

Methods for File I/O

Given below are some methods and their syntax for various file I/O operations:...

Examples

Write a File...

Different Types of Files

...