-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileIO.rs
69 lines (47 loc) · 1.84 KB
/
fileIO.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use std::error::Error;
use std::io::prelude::*;
use std::fs::File;
// Write a message to the given file name.
// If the file does not extist, create it.
// The first argument (filename:String) is the name of the file
// and the second argument (message:String) is the message will be stored.
pub fn write_file( filename:String, message:String ) {
// Create the File.
let mut file = match File::create(&filename) {
Err(failure) => panic!("System failed to create File {} because of: {}",
filename,
failure.description()
),
Ok(file) => file,
};
// Write the message into the file.
match file.write_all(message.as_bytes()) {
Err(failure) => {
panic!("couldn't write to {}: {}", filename
, failure.description())
},
Ok(_) => println!("Message successfully stored into {}.", filename),
}
}
// Read the contents of the given file name and return them as a string.
// The argument (filename:String) is the name of the file
pub fn read_file( filename:String ) -> String {
// Open the File.
let mut file = match File::open(&filename) {
Err(failure) => panic!("System failed to create File {} because of: {}",
filename,
failure.description()
),
Ok(file) => file,
};
let mut message = String::new();
// Read the file and store it in message.
match file.read_to_string(&mut message) {
Err(failure) => {
panic!("Couldn't read from {}: {}", filename
, failure.description())
},
Ok(_) => println!("Message successfully read from {}.", filename),
};
message
}