Skip to content

Commit d43dfc5

Browse files
committed
Add Removing a File Example Compile Run Add Output Note File Deleted from folder
1 parent 089968b commit d43dfc5

File tree

3 files changed

+42
-10
lines changed

3 files changed

+42
-10
lines changed

documentation2/B07-File-Handling.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,3 +161,40 @@ cargo run
161161
```bash
162162
Created a file data.txt
163163
```
164+
165+
Here, we import `std::fs::File` and `std::io::Write` modules for writing to a file. We first create a file `data.txt` with the `File::create("data.txt")` method and bind it to a mutable variable `data_file`.
166+
167+
After we create a file, we write to the file using the `write()` method with the content `"Hello, World!"`.
168+
169+
____
170+
171+
### Removing a File in Rust
172+
173+
To remove or delete a file in Rust, we can use the remove_file() method from the std::fs module.
174+
175+
For example,
176+
177+
```rust
178+
use std::fs;
179+
180+
fn main() {
181+
// Remove a file
182+
fs::remove_file("data.txt").expect("could not remove file");
183+
184+
println!("Removed file data.txt");
185+
}
186+
```
187+
188+
```bash
189+
cargo build
190+
```
191+
192+
```bash
193+
cargo run
194+
```
195+
196+
#### Output
197+
198+
```bash
199+
Removed file data.txt
200+
```

programiz/attempt-02/hello_world/data.txt

Lines changed: 0 additions & 1 deletion
This file was deleted.
Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,8 @@
1-
use std::fs::File;
2-
use std::io::Write;
1+
use std::fs;
32

43
fn main() {
5-
// Create a file
6-
let mut data_file = File::create("data.txt").expect("creation failed");
7-
8-
// Write contents to the file
9-
data_file.write("Hello, World!".as_bytes()).expect("write failed");
10-
11-
println!("Created a file data.txt");
4+
// Remove a file
5+
fs::remove_file("data.txt").expect("could not remove file");
6+
7+
println!("Removed file data.txt");
128
}

0 commit comments

Comments
 (0)