Difference between revisions of "Rust-Programming-Language/C2/Path-Struct/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
Line 40: Line 40:
  
 
|-  
 
|-  
|| Open '''Visual''' '''code editor'''
+
|| Open '''Visual code editor'''
 
|| Let us open the '''Visual Studio code editor'''.
 
|| Let us open the '''Visual Studio code editor'''.
  
Line 76: Line 76:
 
'''Path''' is used to inspect and manipulate file or directory paths in a safe way.
 
'''Path''' is used to inspect and manipulate file or directory paths in a safe way.
  
It''' '''creates a Path instance pointing to "'''hello'''.'''txt'''".  
+
It creates a Path instance pointing to "'''hello.txt'''".  
  
 
At this stage, no file is created or opened.
 
At this stage, no file is created or opened.
  
'''path.exists() '''method checks if '''hello.txt '''actually exists in the file system or not.
+
'''path.exists() '''method checks if '''hello.txt ''' actually exists in the file system or not.
  
'''path.is_file() '''method''' '''checks if the path points to a file.
+
'''path.is_file() '''method checks if the path points to a file.
  
 
'''path.is_dir() '''method checks if the path points to a '''directory'''.
 
'''path.is_dir() '''method checks if the path points to a '''directory'''.
Line 91: Line 91:
 
|| Run the program.
 
|| Run the program.
  
Here the '''hello.txt '''file''' '''does not exist and so it returns false.
+
Here the '''hello.txt '''file does not exist and so it returns false.
 
|-  
 
|-  
 
|| Create hello.txt in the path struct folder.
 
|| Create hello.txt in the path struct folder.
Line 139: Line 139:
  
 
}
 
}
||  
+
|| '''Path::new''' method creates a '''Path''' object pointing to the absolute path.
'''Path::new''' method creates a '''Path''' object pointing to the absolute path.
+
  
'''path.file_name() '''method''' '''gets the last component of the path.
+
'''path.file_name() '''method gets the last component of the path.
  
 
Here it is the filename '''file.txt'''
 
Here it is the filename '''file.txt'''
Line 156: Line 155:
 
Save the program.
 
Save the program.
 
|-  
 
|-  
|| In the terminal, type '''cargo run '''
+
|| In the terminal, type '''cargo run '''.
 
|| In the terminal, type '''cargo run '''to see the output.
 
|| In the terminal, type '''cargo run '''to see the output.
 
|-  
 
|-  
Line 180: Line 179:
  
 
}
 
}
|| We use''' std::io() '''to bring the core utility functions '''stdin() '''and''' stdout().'''
+
|| We use ''' std::io() '''to bring the core utility functions '''stdin() '''and''' stdout().'''
  
 
'''String::new()''' method creates a mutable empty string to store user input.
 
'''String::new()''' method creates a mutable empty string to store user input.
Line 190: Line 189:
 
'''.expect()''' is used here for simple error handling.
 
'''.expect()''' is used here for simple error handling.
  
'''.trim() '''method removes the unwanted characters from the end of input and format it.
+
'''.trim() ''' method removes the unwanted characters from the end of input and format it.
  
 
At last we print '''Hello''' and the input that user enters on the console.
 
At last we print '''Hello''' and the input that user enters on the console.
Line 231: Line 230:
 
'''File::open '''method returns a '''Result enum''' type.
 
'''File::open '''method returns a '''Result enum''' type.
  
If the file exists and opens successfully it returns the '''OK '''type.
+
If the file exists and opens successfully it returns the '''OK ''' type.
  
 
If the file doesn’t exist (or another error happens), '''e''' holds the error details.
 
If the file doesn’t exist (or another error happens), '''e''' holds the error details.

Latest revision as of 21:52, 23 November 2025

Visual Cue Narration
Slide 1

Title Slide

Welcome to the Spoken Tutorial on Path Struct in Rust.
Slide 2

Learning Objectives

In this tutorial, we will learn about,
  • Path Struct and
  • Common methods of Path struct
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

Path Struct

  • Path is a struct in Rust’s standard library (std::path::Path)
  • It is used to represent file system’s path.
  • A Path does not actually open or read files.
Open Visual code editor Let us open the Visual Studio code editor.
In the menu bar, click on Terminal and select New Terminal.

> cd Desktop/MyRustProject

> cargo new pathstruct

I have created the pathstruct project as explained earlier.

We will see how Rust interacts with files and folders using the Path struct.

Point to the main.rs file. In the main.rs file, copy and paste the code from the Code file.
use std::path::Path;

fn main() {

let path = Path::new("hello.txt");

println!("Exists: {}", path.exists());

println!("Is file: {}", path.is_file());

println!("Is directory: {}", path.is_dir());

}

This code checks if a file exists and also whether it’s a file or directory.

We import the Path struct from the std::path module.

Path is used to inspect and manipulate file or directory paths in a safe way.

It creates a Path instance pointing to "hello.txt".

At this stage, no file is created or opened.

path.exists() method checks if hello.txt actually exists in the file system or not.

path.is_file() method checks if the path points to a file.

path.is_dir() method checks if the path points to a directory.

Save the program.

Type cargo run to run the program Run the program.

Here the hello.txt file does not exist and so it returns false.

Create hello.txt in the path struct folder.

Type cargo run at the terminal prompt.

Let us create the file hello.txt in the working folder.

Run the same code and check the output.

Next we will see more methods that are used with Path struct.
Select all >> press Delete key Clear the window and copy and paste the code from the code file.
use std::path::Path;

fn main() {

let path = Path::new("/home/nirmala/docs/file.txt");

println!("Full path: {:?}", path);

// Get the file name (last component)

if let Some(filename) = path.file_name() {

println!("File name: {}", filename.to_string_lossy());

}

// Get the parent directory

if let Some(parent) = path.parent() {

println!("Parent directory: {:?}", parent);

}

// Get the extension

if let Some(ext) = path.extension() {

println!("Extension: {}", ext.to_string_lossy());

}

}

Path::new method creates a Path object pointing to the absolute path.

path.file_name() method gets the last component of the path.

Here it is the filename file.txt

to_string_lossy() function converts it into a human-readable String.

path.parent() gets the parent directory of the path.

path.extension() gets the file extension.

Here the extension is .txt

Save the program.

In the terminal, type cargo run . In the terminal, type cargo run to see the output.
Next we will know how to get the input from the user.

These operations deal with reading from the keyboard and writing to the terminal.

Clear the code window and replace the code from the code file as shown.
use std::io;

fn main() {

let mut input = String::new();

println!("Enter your name:");

io::stdin().read_line(&mut input).expect("Failed to read line");

println!("Hello, {}", input.trim());

}

We use std::io() to bring the core utility functions stdin() and stdout().

String::new() method creates a mutable empty string to store user input.

Next it prompts the user to type his/her name.

read_line waits for the user to type and press Enter.

.expect() is used here for simple error handling.

.trim() method removes the unwanted characters from the end of input and format it.

At last we print Hello and the input that user enters on the console.

Save the program.

In the terminal, type cargo run

Enter the name

Type name >> Press Enter.

In the terminal, type cargo run.

It prompts to enter the name.

Type your name and press Enter.

It prints Hello and the entered name as output.

Next we will see how to handle errors in file operations
use std::fs::File;

fn main() {

match File::open("non_existent.txt") {

Ok(_) => println!("File opened successfully."),

Err(e) => println!("Error opening file: {}", e),

}

}

Copy and paste the code from the code file.


File::open method returns a Result enum type.

If the file exists and opens successfully it returns the OK type.

If the file doesn’t exist (or another error happens), e holds the error details.

Save the program.

Type cargo run

Point to the error message.

Run the program and check the output.

We can see an error message “Error opening file: No such file or directory”.

Slide 6

Summary

This brings us to the end of this tutorial.

Let us summarize.

Slide 7

Assignment

As an Assignment

Write a Rust program that:

1. Asks the user to enter a file path

2. Prints the following information using methods from std::path::Path module.

Slide 8

Thank You

Thanks for joining.

Contributors and Content Editors

Madhurig, Nirmala Venkat