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

From Script | Spoken-Tutorial
Jump to: navigation, search
 
Line 14: Line 14:
 
|| In this tutorial, we will learn about:
 
|| In this tutorial, we will learn about:
 
* File operations
 
* File operations
* Input and Outputoperations
+
* Input and Output operations
  
 
|-  
 
|-  
Line 37: Line 37:
  
 
|| '''File Input/Output'''operations are done using the below modules from the Standard Library  
 
|| '''File Input/Output'''operations are done using the below modules from the Standard Library  
* '''std::fs '''is a module for file handling  
+
* '''std::fs ''' is a module for file handling  
*  '''std::io '''is a module for reading and writing  
+
*  '''std::io ''' is a module for reading and writing  
  
 
|-  
 
|-  
Line 66: Line 66:
  
 
}
 
}
|| We import the '''File'''struct from the '''std:fs'''module.
+
|| We import the '''File struct''' from the '''std:fs''' module.
  
'''File'''is used to create, openand workwith files.
+
'''File''' is used to create, open and work with files.
  
Then we import the '''io'''module and '''write'''the trait.
+
Then we import the '''io'''module and '''write''' the trait.
  
Here '''self'''means importing''' std::io '''itself as''' io.'''
+
Here '''self''' means importing''' std::io '''itself as ''' io.'''
  
In the main function, '''File::create()'''method creates a new file called '''output.txt.'''
+
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.
+
If it already exists, it truncates it before writing, otherwise creates a new file.
  
'''Write_all '''writes all the''' bytes'''from the given byte string into the file.
+
'''Write_all '''writes all the ''' bytes''' from the given byte string into the file.
  
 
The''' b''' before the string literal means that we are writing '''raw bytes''', not a String.  
 
The''' b''' before the string literal means that we are writing '''raw bytes''', not a String.  
Line 93: Line 93:
 
|-  
 
|-  
 
|| Open and show the file
 
|| Open and show the file
|| In the terminal,type '''cargo run '''to see the output.
+
|| 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.
 
|-  
 
|-  
 
||  
 
||  
Line 120: Line 122:
  
 
}
 
}
|| We import the '''Read trait '''from the '''io'''module.
+
|| We import the '''Read trait ''' from the '''io''' module.
  
 
In the main function, we return io::Result<()>.
 
In the main function, we return io::Result<()>.
  
File::open()method opens''' output.txt '''filein '''read-only'''mode.
+
'''File::open()''' method opens ''' output.txt '''filein ''' read-only'''mode.
  
 
? propagates an error if the file doesn’t exist or can’t be opened.
 
? propagates an error if the file doesn’t exist or can’t be opened.
Line 139: Line 141:
 
|-  
 
|-  
 
|| To run type '''cargo run''' in the terminal.
 
|| To run type '''cargo run''' in the terminal.
|| In the terminal, type '''cargo run'''
+
|| In the terminal, type '''cargo run'''.
  
We can see the content of the file''' output.txt '''is displayed.
+
We can see the content of the file ''' output.txt '''is displayed.
 
|-  
 
|-  
 
||  
 
||  
Line 173: Line 175:
 
Operations like appending, reading and writing can be done simultaneously.
 
Operations like appending, reading and writing can be done simultaneously.
  
'''.append(true)method '''enables the append mode.
+
'''.append(true)method ''' enables the append mode.
 +
 
 +
New data will be appended at the end of the file instead of overwriting.
  
New data will be appendedat the end of the file instead of overwriting.
+
It opens '''output.txt  file'''  with the ? which handles errors.
  
It opens '''output.txt '''file''' '''with the ? which handles errors (For example., if the file doesn’t exist).
+
For example., if the file doesn’t exist.
  
 
'''file.write_all '''writes a newline followed by the text "This is an appended line."  
 
'''file.write_all '''writes a newline followed by the text "This is an appended line."  
Line 188: Line 192:
 
We see the message “'''Data added to the file”'''.
 
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.
Line 209: Line 213:
  
 
}
 
}
|| '''remove_file'''method deletes the file named '''output.txt ''' from the current directory.
+
|| '''remove_file''' method 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 doesn’t exist or if you don’t have permission, it returns an error.
Line 234: Line 238:
 
Write a Rust program to do the following steps in order:
 
Write a Rust program to do the following steps in order:
  
* Create a file named '''notes.txt.'''
+
* Create a file named '''notes.txt'''
 
* Write the below text into the file:
 
* Write the below text into the file:
 
* Reopen the same file in append mode and add one more line:
 
* 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.
+
* Read back the entire contents of the file and print them on the console.
  
 
|-  
 
|-  

Latest revision as of 17:55, 4 December 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 Output operations
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 File struct from the std:fs module.

File is used to create, open and work with files.

Then we import the iomodule and write the trait.

Here self means 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 bytes from 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 io module.

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 appended at 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_file method 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 contents of the file and print them on the console.
Slide 9

Thank You

Thanks for joining.

Contributors and Content Editors

Madhurig, Nirmala Venkat