Skip to content

Commit c9bdd4b

Browse files
committed
Add Appending to a File Example Add data txt file with text to hello world folder
Reason To allow main rs to append to file and run without error
1 parent 8e28659 commit c9bdd4b

File tree

3 files changed

+59
-5
lines changed

3 files changed

+59
-5
lines changed

documentation2/B07-File-Handling.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,3 +221,47 @@ could not remove file: Os { code: 2, kind: NotFound, message: "The system cannot
221221
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
222222
error: process didn't exit successfully: `target\debug\hello_world.exe` (exit code: 101)
223223
```
224+
225+
____
226+
227+
### Appending to a File in Rust
228+
229+
To append to a file in Rust, we should open the file in append mode. We can use the `append()` method in `std::fs::OpenOptions` which opens a file for appending.
230+
231+
Then, we can use the `write()` method in `std::io::Write` trait to write data to the file.
232+
233+
Let's look at an example.
234+
235+
```rust
236+
use std::fs::OpenOptions;
237+
use std::io::Write;
238+
239+
fn main() {
240+
// Open a file with append option
241+
let mut data_file = OpenOptions::new()
242+
.append(true)
243+
.open("data.txt")
244+
.expect("cannot open file");
245+
246+
// Write to a file
247+
data_file
248+
.write("I am learning Rust!".as_bytes())
249+
.expect("write failed");
250+
251+
println!("Appended content to a file");
252+
}
253+
```
254+
255+
```bash
256+
cargo build
257+
```
258+
259+
```bash
260+
cargo run
261+
```
262+
263+
#### Output
264+
265+
```bash
266+
Appended content to a file
267+
```
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The quick brown fox jumps over the lazy dog.\nI am learning Rust!
Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,17 @@
1-
use std::fs;
1+
use std::fs::OpenOptions;
2+
use std::io::Write;
23

34
fn main() {
4-
// Remove a file
5-
fs::remove_file("data.txt").expect("could not remove file");
6-
7-
println!("Removed file data.txt");
5+
// Open a file with append option
6+
let mut data_file = OpenOptions::new()
7+
.append(true)
8+
.open("data.txt")
9+
.expect("cannot open file");
10+
11+
// Write to a file
12+
data_file
13+
.write("I am learning Rust!".as_bytes())
14+
.expect("write failed");
15+
16+
println!("Appended content to a file");
817
}

0 commit comments

Comments
 (0)