Выбрать главу

Be sure to check at other Path methods (posix::Path or windows::Path) and the Metadata struct.

OsStr and Metadata.

The File struct represents a file that has been opened (it wraps a file descriptor), and gives read and/or write access to the underlying file.

Since many things can go wrong when doing file I/O, all the File methods return the io::Result<T> type, which is an alias for Result<T, io::Error>.

This makes the failure of all I/O operations explicit. Thanks to this, the programmer can see all the failure paths, and is encouraged to handle them in a proactive manner.

The open static method can be used to open a file in read-only mode.

A File owns a resource, the file descriptor and takes care of closing the file when it is droped.

use std::fs::File;

use std::io::prelude::*;

use std::path::Path;

fn main() {

// Create a path to the desired file

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

let display = path.display();

// Open the path in read-only mode, returns `io::Result<File>`

let mut file = match File::open(&path) {

Err(why) => panic!("couldn't open {}: {}", display, why),

Ok(file) => file,

};

// Read the file contents into a string, returns `io::Result<usize>`

let mut s = String::new();

match file.read_to_string(&mut s) {

Err(why) => panic!("couldn't read {}: {}", display, why),

Ok(_) => print!("{} contains:\n{}", display, s),

}

// `file` goes out of scope, and the "hello.txt" file gets closed

}

הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Here's the expected successful output:

$ echo "Hello World!" > hello.txt

$ rustc open.rs && ./open

hello.txt contains:

Hello World!

(You are encouraged to test the previous example under different failure conditions: hello.txt doesn't exist, or hello.txt is not readable, etc.)

The create static method opens a file in write-only mode. If the file already existed, the old content is destroyed. Otherwise, a new file is created.

static LOREM_IPSUM: &str =

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

";

use std::fs::File;

use std::io::prelude::*;

use std::path::Path;

fn main() {

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

let display = path.display();

// Open a file in write-only mode, returns `io::Result<File>`

let mut file = match File::create(&path) {

Err(why) => panic!("couldn't create {}: {}", display, why),

Ok(file) => file,

};

// Write the `LOREM_IPSUM` string to `file`, returns `io::Result<()>`

match file.write_all(LOREM_IPSUM.as_bytes()) {

Err(why) => panic!("couldn't write to {}: {}", display, why),

Ok(_) => println!("successfully wrote to {}", display),

}

}

Here's the expected successful output:

$ rustc create.rs && ./create

successfully wrote to lorem_ipsum.txt

$ cat lorem_ipsum.txt

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod

tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,

quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo

consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse

cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non

proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

(As in the previous example, you are encouraged to test this example under failure conditions.)

There is OpenOptions struct that can be used to configure how a file is opened.

The method lines() returns an iterator over the lines of a file.

File::open expects a generic, AsRef<Path>. That's what read_lines() expects as input.

use std::fs::File;

use std::io::{self, BufRead};

use std::path::Path;

fn main() {

// File hosts must exist in current path before this produces output

if let Ok(lines) = read_lines("./hosts") {

// Consumes the iterator, returns an (Optional) String

for line in lines {

if let Ok(ip) = line {

println!("{}", ip);

}

}

}

}

// The output is wrapped in a Result to allow matching on errors

// Returns an Iterator to the Reader of the lines of the file.

fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>

where P: AsRef<Path>, {

let file = File::open(filename)?;

Ok(io::BufReader::new(file).lines())