mirror of
https://github.com/LCTT/TranslateProject.git
synced 2025-01-25 23:11:02 +08:00
translated
This commit is contained in:
parent
9918aa6481
commit
7e745ce427
@ -1,110 +0,0 @@
|
||||
[#]: subject: "How to read and write files in Rust"
|
||||
[#]: via: "https://opensource.com/article/23/1/read-write-files-rust"
|
||||
[#]: author: "Stephan Avenwedde https://opensource.com/users/hansic99"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
How to read and write files in Rust
|
||||
======
|
||||
|
||||
Knowing how to read and write files can be useful for various purposes. In Rust, this task is done using the file system module ([std::fs][1]) in the standard library. In this article, I'll give you an overview on how to use this module.
|
||||
|
||||
To demonstrate this task, I prepared example code which is also available on [GitHub][2].
|
||||
|
||||
### Preparation
|
||||
|
||||
When using Rust, a function that fails returns the [Result][3] type. The file system module in particular returns the specialized type [std::io::Result<T, Error>][4]. With this knowledge, you can return the same type from the `main()` function:
|
||||
|
||||
```
|
||||
fn main() -> std::io::Result<()> {
|
||||
/* ...code comes here... */
|
||||
```
|
||||
|
||||
### Writing Rust files
|
||||
|
||||
Performing file I/O-operations in Rust is relatively easy. Writing to a file can be simplified to one line:
|
||||
|
||||
```
|
||||
use std::fs;
|
||||
fs::write("favorite_websites.txt", b"opensource.com")?;
|
||||
Ok(())
|
||||
```
|
||||
|
||||
Using the error propagation operator `(?)`, the error information gets passed on to the calling function where the error can subsequently be handled. As `main()` is the only other function in the call stack, the error information gets passed on to the console output in case the write operation failed.
|
||||
|
||||
The syntax of the [fs::write][5] function is quite forward. The first argument is the file path, which must be the type [std::path::Path][6]. The second argument is the content, which is actually a slice of bytes (`[u8]`). Rust converts the arguments passed into the correct type. Luckily, these types are basically the only types dealt with in the following examples.
|
||||
|
||||
A more concise access of the write operation can be achieved using the file descriptor type [std::fs::File][7]:
|
||||
|
||||
```
|
||||
let mut file = fs::File::create("favorite_websites.txt")?;
|
||||
file.write_all(b"opensource.com\n")?;
|
||||
Ok(())
|
||||
```
|
||||
|
||||
As the file type implements the [Write][8] trait, it is possible to use the associated methods to write to the file. However, the `create` method can overwrite an already existing file.
|
||||
|
||||
To get even more control of the file descriptor, the type [std::fs::OpenOptions][9] must be used. This provides opening modes similar to the ones in other languages:
|
||||
|
||||
```
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open("favorite_websites.txt")?;
|
||||
|
||||
file.write_all(b"sourceforge.net\n")?;
|
||||
```
|
||||
|
||||
### Reading Rust files
|
||||
|
||||
What applies to writing also applies to reading. Reading can also be done with a simple one-line of code:
|
||||
|
||||
```
|
||||
let websites = fs::read_to_string("favorite_websites.txt")?;
|
||||
```
|
||||
|
||||
The above line reads the content of the file and returns a string. In addition to reading a string, there is also the [std::fs::read][10] function which reads the data into a vector of bytes if the file contains binary data.
|
||||
|
||||
The next example shows how to read the content of the file into memory and subsequently print it line by line to a console:
|
||||
|
||||
```
|
||||
let file = fs::File::open("favorite_websites.txt")?;
|
||||
let lines = io::BufReader::new(file).lines();
|
||||
|
||||
for line in lines {
|
||||
if let Ok(_line) = line {
|
||||
println!(">>> {}", _line);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Summary
|
||||
|
||||
If you are already familiar with other programming languages, you may have noticed that there is `no close-`function (or something similar) that releases the file handle. In Rust, the file handle is released as soon as the related variable goes out of scope. To define the closing behavior, a scope `({ })` around the file representation can be applied. I recommend that you get familiar with [Read][11] and [Write][8] trait as you can find this trait implemented in many other types.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/23/1/read-write-files-rust
|
||||
|
||||
作者:[Stephan Avenwedde][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[译者ID](https://github.com/译者ID)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/hansic99
|
||||
[b]: https://github.com/lkxed
|
||||
[1]: https://doc.rust-lang.org/std/fs/
|
||||
[2]: https://github.com/hANSIc99/rust_file_io
|
||||
[3]: https://doc.rust-lang.org/std/result/enum.Result.html
|
||||
[4]: https://doc.rust-lang.org/std/io/type.Result.html
|
||||
[5]: https://doc.rust-lang.org/std/fs/fn.write.html
|
||||
[6]: https://doc.rust-lang.org/std/path/struct.Path.html
|
||||
[7]: https://doc.rust-lang.org/std/fs/struct.File.html
|
||||
[8]: https://doc.rust-lang.org/std/io/trait.Write.html
|
||||
[9]: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#
|
||||
[10]: https://doc.rust-lang.org/std/fs/fn.read.html
|
||||
[11]: https://doc.rust-lang.org/std/io/trait.Read.html
|
@ -0,0 +1,111 @@
|
||||
[#]: subject: "How to read and write files in Rust"
|
||||
[#]: via: "https://opensource.com/article/23/1/read-write-files-rust"
|
||||
[#]: author: "Stephan Avenwedde https://opensource.com/users/hansic99"
|
||||
[#]: collector: "lkxed"
|
||||
[#]: translator: "geekpi"
|
||||
[#]: reviewer: " "
|
||||
[#]: publisher: " "
|
||||
[#]: url: " "
|
||||
|
||||
如何在 Rust 中读取和写入文件
|
||||
======
|
||||
|
||||
知道如何读写文件对各种用途都很有用。在 Rust 中,这项任务是通过标准库中的文件系统模块([std::fs][1])完成的。在这篇文章中,我将向你介绍如何使用这个模块。
|
||||
|
||||
为了演示这项任务,我准备了一些示例代码,也可以在 [GitHub][2] 上找到。
|
||||
|
||||
### 准备工作
|
||||
|
||||
在使用 Rust 时,失败的函数会返回 [Result][3] 类型。尤其是文件系统模块会返回专门的类型 [std::io::Result<T, Error>][4]。有了这些知识,你可以从 `main()` 函数中返回相同的类型:
|
||||
|
||||
```
|
||||
fn main() -> std::io::Result<()> {
|
||||
/* ...code comes here... */
|
||||
```
|
||||
|
||||
### Rust 文件写入
|
||||
|
||||
在 Rust 中执行文件的 I/O 操作是相对容易的。写入文件可以简化为一行:
|
||||
|
||||
```
|
||||
use std::fs;
|
||||
fs::write("favorite_websites.txt", b"opensource.com")?;
|
||||
Ok(())
|
||||
```
|
||||
|
||||
使用错误传播操作符 `(?)`,错误信息被传递到调用函数中,随后可以处理错误。由于 `main()` 是调用栈中唯一的其他函数,如果写操作失败,错误信息将被传递到控制台输出。
|
||||
|
||||
[fs::write][5] 函数的语法是非常先进的。第一个参数是文件路径,它必须是 [std::path::Path][6] 类型。第二个参数是内容,它实际上是一个字节切片(`[u8]`)。Rust 将传递的参数转换为正确的类型。幸运的是,这些类型基本上是下面的例子中所处理的唯一类型。
|
||||
|
||||
使用文件描述符类型 [std::fs::File][7] 可以实现对写操作更简洁的访问:
|
||||
|
||||
```
|
||||
let mut file = fs::File::create("favorite_websites.txt")?;
|
||||
file.write_all(b"opensource.com\n")?;
|
||||
Ok(())
|
||||
```
|
||||
|
||||
由于文件类型实现了 [Write][8] 特性,所以可以使用相关的方法来写入文件。然而,`create` 方法可以覆盖一个已经存在的文件。
|
||||
|
||||
为了获得对文件描述符的更多控制,必须使用 [std::fs::OpenOptions][9] 类型。这提供了类似于其他语言中的打开模式:
|
||||
|
||||
```
|
||||
let mut file = fs::OpenOptions::new()
|
||||
.append(true)
|
||||
.open("favorite_websites.txt")?;
|
||||
|
||||
file.write_all(b"sourceforge.net\n")?;
|
||||
```
|
||||
|
||||
### Rust 文件读取
|
||||
|
||||
适用于写的东西也适用于读。读取也可以通过简单的一行代码来完成:
|
||||
|
||||
```
|
||||
let websites = fs::read_to_string("favorite_websites.txt")?;
|
||||
```
|
||||
|
||||
以上一行读取文件的内容并返回一个字符串。除了读取字符串,还有 [std::fs::read][10] 函数,如果文件包含二进制数据,该函数会将数据读成一个字节向量。
|
||||
|
||||
下一个例子显示了如何将文件的内容读入内存,随后逐行打印到控制台:
|
||||
|
||||
```
|
||||
let file = fs::File::open("favorite_websites.txt")?;
|
||||
let lines = io::BufReader::new(file).lines();
|
||||
|
||||
for line in lines {
|
||||
if let Ok(_line) = line {
|
||||
println!(">>> {}", _line);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 总结
|
||||
|
||||
如果你已经熟悉了其他编程语言,你可能已经注意到没有 `close-` 函数(或类似的)来释放文件句柄。在 Rust 中,当相关变量超出作用域,文件句柄就会被释放。为了定义关闭行为,可以在文件表示的周围应用作用域 `({ })`。我建议你熟悉 [Read][11] 和 [Write][8] 特性,因为你可以在许多其他类型中找到这个特性的实现。
|
||||
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
via: https://opensource.com/article/23/1/read-write-files-rust
|
||||
|
||||
作者:[Stephan Avenwedde][a]
|
||||
选题:[lkxed][b]
|
||||
译者:[geekpi](https://github.com/geekpi)
|
||||
校对:[校对者ID](https://github.com/校对者ID)
|
||||
|
||||
本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出
|
||||
|
||||
[a]: https://opensource.com/users/hansic99
|
||||
[b]: https://github.com/lkxed
|
||||
[1]: https://doc.rust-lang.org/std/fs/
|
||||
[2]: https://github.com/hANSIc99/rust_file_io
|
||||
[3]: https://doc.rust-lang.org/std/result/enum.Result.html
|
||||
[4]: https://doc.rust-lang.org/std/io/type.Result.html
|
||||
[5]: https://doc.rust-lang.org/std/fs/fn.write.html
|
||||
[6]: https://doc.rust-lang.org/std/path/struct.Path.html
|
||||
[7]: https://doc.rust-lang.org/std/fs/struct.File.html
|
||||
[8]: https://doc.rust-lang.org/std/io/trait.Write.html
|
||||
[9]: https://doc.rust-lang.org/std/fs/struct.OpenOptions.html#
|
||||
[10]: https://doc.rust-lang.org/std/fs/fn.read.html
|
||||
[11]: https://doc.rust-lang.org/std/io/trait.Read.html
|
Loading…
Reference in New Issue
Block a user