Difference between revisions of "Rust-Programming-Language/C2/File-Handling/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
(Created page with "{| border="1" |- || '''Visual Cue''' || '''Narration''' |- || '''Slide 1''' || <span style="color:#000000;">Welcome to the Spoken Tutorial on </span><span style="color:#000000...")
 
Line 5: Line 5:
 
|-
 
|-
 
|| '''Slide 1'''
 
|| '''Slide 1'''
|| <span style="color:#000000;">Welcome to the Spoken Tutorial on </span><span style="color:#000000;">'''File Handling '''</span><span style="color:#000000;">in </span><span style="color:#000000;">'''Rust.'''</span>
+
'''
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
Title Slide'''
|| <div style="color:#000000;">'''Slide 2'''</div>
+
|| Welcome to the Spoken Tutorial on '''File Handling '''in '''Rust.'''
 +
|-  
 +
|| '''Slide 2'''
  
<div style="color:#000000;">'''Learning Objectives'''</div>
+
'''Learning Objectives'''
 
|| In this tutorial, we will learn about:
 
|| In this tutorial, we will learn about:
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">File operations</div>
+
* File operations
* <div style="margin-left:1.27cm;margin-right:0cm;"><span style="color:#000000;">Input and </span>Output<span style="color:#000000;"> operations</span></div>
+
* Input and Outputoperations
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.101cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">'''Slide 3'''</div>
+
|| '''Slide 3'''
  
<div style="color:#000000;">'''System Requirements'''</div>
+
'''System Requirements'''
|| <div style="color:#000000;">To record this tutorial I’m using the following setup.</div>
+
|| To record this tutorial I’m using the following setup.
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.101cm;padding-right:0.191cm;"
+
|-  
|| <span style="color:#000000;">'''Slide'''</span><span style="color:#000000;"> </span><span style="color:#000000;">'''5'''</span>
+
|| '''Slide 4'''
  
<div style="color:#000000;">'''Code Files'''</div>
+
'''Code Files'''
 
||
 
||
* <div style="color:#000000;">The following code file is required to practise this tutorial.</div>
+
* The following code file is required to practise this tutorial.
* <div style="color:#000000;">This file is provided in the Code Files link of this tutorial page.</div>
+
* This file is provided in the Code Files link of this tutorial page.
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.101cm;padding-right:0.191cm;"
+
|-  
|| <span style="color:#000000;">'''Slide</span> 6'''
+
|| '''Slide 5'''
  
<div style="color:#000000;">'''File I/O – Standard Library'''</div>
+
'''File I/O – Standard Library'''
  
<div style="color:#001d35;"></div>
 
  
|| <span style="color:#000000;">'''File Input/Output'''</span><span style="color:#000000;"> operations are done </span>using <span style="color:#000000;">the below modules from the Standard Library </span>
+
|| '''File Input/Output'''operations are done using the below modules from the Standard Library  
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">'''std::fs '''is a module for file handling </div>
+
* '''std::fs '''is a module for file handling  
* <div style="margin-left:1.27cm;margin-right:0cm;"><span style="color:#000000;">'''std::io '''</span><span style="color:#000000;">is a module for reading and writing </span></div>
+
* '''std::io '''is a module for reading and writing  
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <span style="color:#000000;">Open </span><span style="color:#000000;">'''Visual'''</span><span style="color:#000000;"> </span><span style="color:#000000;">'''code editor'''</span>
+
|| Open '''Visual''''''code editor'''
 
|| Open the '''Visual Studio code editor.'''
 
|| Open the '''Visual Studio code editor.'''
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
||  
 
|| I have created the '''filehandling''' project as explained earlier.
 
|| I have created the '''filehandling''' project as explained earlier.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <span style="color:#000000;">Point to the </span><span style="color:#000000;">'''main.rs'''</span><span style="color:#000000;"> file.</span>
+
|| Point to the '''main.rs'''file.
  
|| <span style="background-color:#ffffff;color:#000000;">In the </span><span style="background-color:#ffffff;color:#000000;">'''main.rs '''</span><span style="background-color:#ffffff;color:#000000;">file, copy and paste the code from the Code file.</span>
+
|| In the '''main.rs '''file, copy and paste the code from the Code file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">use std::fs::File;</div>
+
|| use std::fs::File;
  
<div style="color:#000000;">use std::io::{self, Write};</div>
+
use std::io::{self, Write};
  
<div style="color:#000000;">fn main() -> io::Result<()> {</div>
+
fn main() -> io::Result<()> {
  
<div style="color:#000000;">let mut file = File::create("output.txt")?; // Create or overwrites file</div>
+
let mut file = File::create("output.txt")?; // Create or overwrites file
  
<div style="color:#000000;">file.write_all(b"Hello, Rust file writing!")?; // Write bytes to file</div>
+
file.write_all(b"Hello, Rust file writing!")?; // Write bytes to file
  
<div style="color:#000000;">println!("Data written to file");</div>
+
println!("Data written to file");
  
<div style="color:#000000;">Ok(())</div>
+
Ok(())
  
<div style="color:#000000;">}</div>
+
}
|| <span style="color:#000000;">We import the </span><span style="color:#000000;">'''File'''</span><span style="color:#000000;"> struct from the </span><span style="color:#000000;">'''std:fs'''</span><span style="color:#000000;"> module.</span>
+
|| We import the '''File'''struct from the '''std:fs'''module.
  
<span style="color:#000000;">'''File'''</span><span style="color:#000000;"> is used t</span>o <span style="color:#000000;">creat</span>e<span style="color:#000000;">, </span>open<span style="color:#000000;"> and </span>work<span style="color:#000000;"> with files.</span>
+
'''File'''is used to create, openand workwith files.
  
<span style="color:#000000;">Then we import the </span><span style="color:#000000;">'''io'''</span><span style="color:#000000;"> module and </span><span style="color:#000000;">'''write'''</span><span style="color:#000000;"> the trait.</span>
+
Then we import the '''io'''module and '''write'''the trait.
  
<span style="color:#000000;">Here </span><span style="color:#000000;">'''self'''</span><span style="color:#000000;"> means </span>i<span style="color:#000000;">mporting</span><span style="color:#000000;">''' std::io '''</span><span style="color:#000000;">itself as</span><span style="color:#000000;">''' io.'''</span>
+
Here '''self'''means importing''' std::io '''itself as''' io.'''
  
<span style="color:#000000;">In the main function,</span><span style="color:#188038;"> </span><span style="color:#000000;">'''File::create()'''</span><span style="color:#000000;"> method creates a new file called </span><span style="color:#000000;">'''output.txt.'''</span>
+
In the main function, '''File::create()'''method creates a new file called '''output.txt.'''
  
<div style="color:#000000;">If it already exists, it truncates it before writing. otherwise creates a new file.</div>
+
If it already exists, it truncates it before writing. otherwise creates a new file.
  
<span style="color:#000000;">'''Write_all '''</span><span style="color:#000000;">writes all the</span><span style="color:#000000;">''' bytes'''</span><span style="color:#000000;"> from the given byte string into the file.</span>
+
'''Write_all '''writes all the''' bytes'''from the given byte string into the file.
  
<span style="color:#000000;">The</span><span style="color:#000000;">''' b'''</span><span style="color:#000000;"> before the string literal means that we are writing </span><span style="color:#000000;">'''raw bytes'''</span><span style="color:#000000;">, not a </span><span style="color:#188038;">String</span><span style="color:#000000;">. </span>
+
The''' b''' before the string literal means that we are writing '''raw bytes''', not a String.  
  
<div style="color:#000000;">This is often safer and faster for low-level writing.</div>
+
This is often safer and faster for low-level writing.
  
<span style="color:#000000;">The </span><span style="color:#188038;">?</span><span style="color:#000000;"> operator is used to handle any write failure.</span>
+
The ? operator is used to handle any write failure.
  
<span style="color:#000000;">After successful writing, we </span>print<span style="color:#000000;"> a success</span><span style="color:#000000;">ful </span><span style="color:#000000;">message.</span>
+
After successful writing, we print a successful message.
  
W<span style="color:#000000;">e </span>return the '''Ok<span style="color:#000000;">()'''</span><span style="color:#000000;"> method variant to signal that everything worked without errors.</span>
+
We return the '''Ok()''' method variant to signal that everything worked without errors.
  
<div style="color:#000000;">Save the file.</div>
+
Save the file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
 
|| Open and show the file
 
|| Open and show the file
|| <span style="color:#000000;">In the terminal</span>,<span style="color:#000000;"> type </span><span style="color:#000000;">'''cargo run '''</span><span style="color:#000000;">to see the output.</span>
+
|| In the terminal,type '''cargo run '''to see the output.
  
 
Let us open the '''output.txt.''' We can see the data written to the file.
 
Let us open the '''output.txt.''' We can see the data written to the file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#252525;" |  
+
||  
| style="color:#000000;" | Next let us see how to read from a file.
+
|| Next let us see how to read from a file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#252525;" |  
+
|| Delete the code and copy-paste the code from the code file.
|| <span style="color:#252525;">Clear the code window and r</span><span style="color:#000000;">eplace the code from the code file as shown</span><span style="color:#252525;">.</span>
+
|| Clear the code window and replace the code from the code file as shown.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">use std::fs::File;</div>
+
|| use std::fs::File;
  
<div style="color:#000000;">use std::io::{self, Read};</div>
+
use std::io::{self, Read};
  
<div style="color:#000000;">fn main() -> io::Result<()> {</div>
+
fn main() -> io::Result<()> {
  
<div style="color:#000000;">let mut file = File::open("output.txt")?; // Open file in read-only mode</div>
+
let mut file = File::open("output.txt")?; // Open file in read-only mode
  
<div style="color:#000000;">let mut contents = String::new();</div>
+
let mut contents = String::new();
  
<div style="color:#000000;">file.read_to_string(&mut contents)?; // Read file into a string</div>
+
file.read_to_string(&mut contents)?; // Read file into a string
  
<div style="color:#000000;">println!("File content: {}", contents);</div>
+
println!("File content: {}", contents);
  
<div style="color:#000000;">Ok(())</div>
+
Ok(())
  
<div style="color:#000000;">}</div>
+
}
|| <span style="color:#000000;">We import t</span>he <span style="color:#000000;">'''Read trait '''</span><span style="color:#000000;">from the </span><span style="color:#000000;">'''io'''</span><span style="color:#000000;"> module.</span>
+
|| We import the '''Read trait '''from the '''io'''module.
  
<span style="color:#000000;">In the main function, we return </span><span style="color:#188038;">io::Result<()></span><span style="color:#000000;">.</span>
+
In the main function, we return io::Result<()>.
  
<span style="color:#188038;">File::open()</span><span style="color:#000000;"> method opens</span><span style="color:#000000;">''' output.txt '''</span><span style="color:#000000;">file</span><span style="color:#000000;"> in </span><span style="color:#000000;">'''read-only'''</span><span style="color:#000000;"> mode.</span>
+
File::open()method opens''' output.txt '''filein '''read-only'''mode.
  
<div style="color:#000000;">? propagates an error if the file doesn’t exist or can’t be opened.</div>
+
? propagates an error if the file doesn’t exist or can’t be opened.
  
<div style="color:#000000;">We create an empty String to hold the file’s contents.</div>
+
We create an empty String to hold the file’s contents.
  
<span style="color:#000000;">Next we create a mutable String named </span><span style="color:#000000;">'''contents'''</span>.
+
Next we create a mutable String named '''contents'''.
  
It stores the <span style="color:#000000;">contents that are read</span>.
+
It stores the contents that are read.
  
<div style="color:#000000;">Finally, we print the file contents to the console.</div>
+
Finally, we print the file contents to the console.
  
<div style="color:#000000;">Save the program.</div>
+
Save the program.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#252525;" |  
+
|| To run type '''cargo run''' in the terminal.
|| <span style="color:#000000;">In the terminal, type </span><span style="color:#000000;">'''cargo run'''</span>
+
|| In the terminal, type '''cargo run'''
  
<span style="color:#000000;">We can see the content of the file</span><span style="color:#000000;">''' output.txt '''</span><span style="color:#000000;">is displayed.</span>
+
We can see the content of the file''' output.txt '''is displayed.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
||  
 
|| Next we will see how to append a file.
 
|| Next we will see how to append a file.
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
|| Delete the code and copy-paste the code from the code file.
|| <span style="color:#252525;">Clear the code window and r</span>eplace the code from the code file as shown<span style="color:#252525;">.</span>
+
|| Clear the code window and replace the code from the code file as shown.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">use std::fs::OpenOptions;</div>
+
|| use std::fs::OpenOptions;
  
<div style="color:#000000;">use std::io::Write;</div>
+
use std::io::Write;
  
f<span style="color:#000000;">n main() -> std::io::Result<()> {</span>
+
fn main() -> std::io::Result<()> {
  
<div style="color:#000000;">let mut file = OpenOptions::new()</div>
+
let mut file = OpenOptions::new()
  
<div style="color:#000000;">.append(true)</div>
+
.append(true)
  
<div style="color:#000000;">.open("output.txt")?;</div>
+
.open("output.txt")?;
  
<span style="color:#000000;">file.write_all(b"\nThis is an appended line.")?;</span>
+
file.write_all(b"\nThis is an appended line.")?;
  
<span style="background-color:#ffffff;">println!("Data added to the file");</span>
+
<span style="background-color:#ffffff;">println!("Data added to the file");
  
<span style="color:#000000;">Ok(())</span>
+
Ok(())
  
<div style="color:#000000;">}</div>
+
}
|| <span style="color:#000000;">'''OpenOptions'''</span><span style="color:#000000;"> is used for more advanced operations</span>.
+
|| '''OpenOptions'''is used for more advanced operations.
  
Operations <span style="color:#000000;">like appending, reading and writing can be done simultaneously.</span>
+
Operations like appending, reading and writing can be done simultaneously.
  
<span style="color:#000000;">'''.append(true)</span><span style="color:#000000;"> </span>method '''<span style="color:#000000;">e</span><span style="color:#000000;">nables the append mode</span>.
+
'''.append(true)method '''enables the append mode.
  
<span style="color:#000000;">New data will be </span>appended<span style="color:#000000;"> at the end of the file instead of overwriting</span>.
+
New data will be appendedat the end of the file instead of overwriting.
  
It o<span style="color:#000000;">pens </span><span style="color:#000000;">'''output.txt '''</span><span style="color:#000000;">file</span><span style="color:#000000;">''' '''</span><span style="color:#000000;">with the ? which handles errors (</span>For example<span style="color:#000000;">., if the file doesn’t exist).</span>
+
It opens '''output.txt '''file''' '''with the ? which handles errors (For example., if the file doesn’t exist).
  
<span style="color:#000000;">'''file.write_all '''</span><span style="color:#000000;">writes a newline followed by the text "This is an appended line." </span>
+
'''file.write_all '''writes a newline followed by the text "This is an appended line."  
  
 
Save the program.
 
Save the program.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
|| Type cargo run in the terminal.
|| <div style="color:#252525;">Run the program to see the output.</div>
+
|| Run the program to see the output.
  
<div style="color:#252525;">We see the message “'''Data added to the file”'''.</div>
+
We see the message “'''Data added to the file”'''.
  
 
Let us open the '''output.txt. '''
 
Let us open the '''output.txt. '''
  
 
We can see the data is added at the end of the file.
 
We can see the data is added at the end of the file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#252525;" |  
+
||  
| style="color:#252525;" | Next we see how to delete a file.
+
|| Next we see how to delete a file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#252525;" |  
+
|| Delete the code and copy-paste the code from the code file.
|| <span style="color:#252525;">Clear the code window and r</span>eplace the code from the code file as shown<span style="color:#252525;">.</span>
+
|| Clear the code window and replace the code from the code file as shown.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">use std::fs;</div>
+
|| use std::fs;
  
<div style="color:#000000;">fn main() -> std::io::Result<()> {</div>
+
fn main() -> std::io::Result<()> {
  
<div style="color:#000000;">fs::remove_file("output.txt")?;</div>
+
fs::remove_file("output.txt")?;
  
<div style="color:#000000;">println!("File deleted");</div>
+
println!("File deleted");
  
<div style="color:#000000;">Ok(())</div>
+
Ok(())
  
<div style="color:#000000;">}</div>
+
}
|| <span style="color:#000000;">'''remove_file'''</span><span style="color:#000000;"> method deletes the file named </span><span style="color:#000000;">'''output.txt '''</span><span style="color:#000000;">from the current directory.</span>
+
|| '''remove_file'''method deletes the file named '''output.txt ''' from the current directory.
  
<span style="color:#000000;">If the file doesn’t exist or if you don’t have permission, </span>it<span style="color:#000000;"> returns an error.</span>
+
If the file doesn’t exist or if you don’t have permission, it returns an error.
  
<div style="color:#000000;">If the file is deleted successfully, “File Deleted” message is printed.</div>
+
If the file is deleted successfully, “File Deleted” message is printed.
  
 
Save the program.
 
Save the program.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
|| Type cargo run in the terminal.
|| <div style="color:#252525;">Run the program to see the output.</div>
+
|| Run the program to see the output.
  
<span style="color:#252525;">We see the message “</span>File Deleted”<span style="color:#252525;">.</span>
+
We see the message “File Deleted”.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
||  
|| <div style="color:#000000;">This brings us to the end of this tutorial.</div>
+
|| This brings us to the end of this tutorial.
  
<div style="color:#000000;">Let us summarize. </div>
+
Let us summarize.  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <span style="color:#000000;">'''Slide 8'''</span>
+
|| '''Slide 8'''
 +
 +
'''Assignment'''
 
|| As an assignment,
 
|| As an assignment,
  
<div style="color:#000000;">Write a Rust program to do the following steps in order:</div>
+
Write a Rust program to do the following steps in order:
 +
 
 +
* Create a file named '''notes.txt.'''
 +
* Write the below text into the file:
 +
* Reopen the same file in append mode and add one more line:
 +
* Read back the entire content of the file and print them on the console.
  
* <div style="margin-left:1.27cm;margin-right:0cm;">Create a file named '''notes.txt.'''</div>
+
|-  
* <div style="margin-left:1.27cm;margin-right:0cm;">Write the below text into the file:</div>
+
|| '''Slide 9'''  
* <div style="margin-left:1.27cm;margin-right:0cm;">Reopen the same file in append mode and add one more line:</div>
+
* <div style="margin-left:1.27cm;margin-right:0cm;">Read back the entire content of the file and print them on the console.</div>
+
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
'''Thank You'''
| style="color:#000000;" | '''Slide 9 Thank You'''
+
|| Thanks for joining.
| style="color:#000000;" | Thanks for joining.
+
 
|-
 
|-
 
|}
 
|}
<div style="margin-left:-1.588cm;margin-right:-1.429cm;"></div>
 

Revision as of 11:10, 13 November 2025

Visual Cue Narration
Slide 1

Title Slide

Welcome to the Spoken Tutorial on File Handling in Rust.
Slide 2

Learning Objectives

In this tutorial, we will learn about:
  • File operations
  • Input and Outputoperations
Slide 3

System Requirements

To record this tutorial I’m using the following setup.
Slide 4

Code Files

  • The following code file is required to practise this tutorial.
  • This file is provided in the Code Files link of this tutorial page.
Slide 5

File I/O – Standard Library


File Input/Outputoperations are done using the below modules from the Standard Library
  • std::fs is a module for file handling
  • std::io is a module for reading and writing
Open Visual'code editor' Open the Visual Studio code editor.
I have created the filehandling project as explained earlier.
Point to the main.rsfile. In the main.rs file, copy and paste the code from the Code file.
use std::fs::File;

use std::io::{self, Write};

fn main() -> io::Result<()> {

let mut file = File::create("output.txt")?; // Create or overwrites file

file.write_all(b"Hello, Rust file writing!")?; // Write bytes to file

println!("Data written to file");

Ok(())

}

We import the Filestruct from the std:fsmodule.

Fileis used to create, openand workwith files.

Then we import the iomodule and writethe trait.

Here selfmeans importing std::io itself as io.

In the main function, File::create()method creates a new file called output.txt.

If it already exists, it truncates it before writing. otherwise creates a new file.

Write_all writes all the bytesfrom the given byte string into the file.

The b before the string literal means that we are writing raw bytes, not a String.

This is often safer and faster for low-level writing.

The ? operator is used to handle any write failure.

After successful writing, we print a successful message.

We return the Ok() method variant to signal that everything worked without errors.

Save the file.

Open and show the file In the terminal,type cargo run to see the output.

Let us open the output.txt. We can see the data written to the file.

Next let us see how to read from a file.
Delete the code and copy-paste the code from the code file. Clear the code window and replace the code from the code file as shown.
use std::fs::File;

use std::io::{self, Read};

fn main() -> io::Result<()> {

let mut file = File::open("output.txt")?; // Open file in read-only mode

let mut contents = String::new();

file.read_to_string(&mut contents)?; // Read file into a string

println!("File content: {}", contents);

Ok(())

}

We import the Read trait from the iomodule.

In the main function, we return io::Result<()>.

File::open()method opens output.txt filein read-onlymode.

? propagates an error if the file doesn’t exist or can’t be opened.

We create an empty String to hold the file’s contents.

Next we create a mutable String named contents.

It stores the contents that are read.

Finally, we print the file contents to the console.

Save the program.

To run type cargo run in the terminal. In the terminal, type cargo run

We can see the content of the file output.txt is displayed.

Next we will see how to append a file.
Delete the code and copy-paste the code from the code file. Clear the code window and replace the code from the code file as shown.
use std::fs::OpenOptions;

use std::io::Write;

fn main() -> std::io::Result<()> {

let mut file = OpenOptions::new()

.append(true)

.open("output.txt")?;

file.write_all(b"\nThis is an appended line.")?;

println!("Data added to the file");

Ok(())

}

OpenOptionsis used for more advanced operations.

Operations like appending, reading and writing can be done simultaneously.

.append(true)method enables the append mode.

New data will be appendedat the end of the file instead of overwriting.

It opens output.txt file with the ? which handles errors (For example., if the file doesn’t exist).

file.write_all writes a newline followed by the text "This is an appended line."

Save the program.

Type cargo run in the terminal. Run the program to see the output.

We see the message “Data added to the file”.

Let us open the output.txt.

We can see the data is added at the end of the file.

Next we see how to delete a file.
Delete the code and copy-paste the code from the code file. Clear the code window and replace the code from the code file as shown.
use std::fs;

fn main() -> std::io::Result<()> {

fs::remove_file("output.txt")?;

println!("File deleted");

Ok(())

}

remove_filemethod deletes the file named output.txt from the current directory.

If the file doesn’t exist or if you don’t have permission, it returns an error.

If the file is deleted successfully, “File Deleted” message is printed.

Save the program.

Type cargo run in the terminal. Run the program to see the output.

We see the message “File Deleted”.

This brings us to the end of this tutorial.

Let us summarize.

Slide 8

Assignment

As an assignment,

Write a Rust program to do the following steps in order:

  • Create a file named notes.txt.
  • Write the below text into the file:
  • Reopen the same file in append mode and add one more line:
  • Read back the entire content of the file and print them on the console.
Slide 9

Thank You

Thanks for joining.

Contributors and Content Editors

Madhurig, Nirmala Venkat