当前位置:网站首页>Rust 文件系统处理之文件读写 - Rust 实践指南
Rust 文件系统处理之文件读写 - Rust 实践指南
2022-06-30 16:59:00 【ruonou.com】
Rust 中,文件读写处理简单而高效。代码也很紧凑,容易阅读。我们从读取文件的字符串行、避免读取写入同一文件、使用内存映射随机访问文件这三个文件处理中的典型案例来了解一下。
文件处理场景大家都很熟悉,因此闲言少叙,直接看代码。
读取文件的字符串行
我们向文件写入三行信息,然后使用 BufRead::lines 创建的迭代器 Lines 读取文件,一次读回一行。File 模块实现了提供 BufReader 结构体的 Read trait。File::create 打开文件 File 进行写入,File::open 则进行读取。
use std::fs::File;
use std::io::{Write, BufReader, BufRead, Error};
fn main() -> Result<(), Error> {
let path = "lines.txt";
let mut output = File::create(path)?;
write!(output, "Rust\n\nFun")?;
let input = File::open(path)?;
let buffered = BufReader::new(input);
for line in buffered.lines() {
println!("{}", line?);
}
Ok(())
}
文件处理中避免读写同一文件
对文件使用 same_file::Handle 结构体,可以测试文件句柄是否等同。在本实例中,将对要读取和写入的文件句柄进行相等性测试。
use same_file::Handle;
use std::fs::File;
use std::io::{BufRead, BufReader, Error, ErrorKind};
use std::path::Path;
fn main() -> Result<(), Error> {
let path_to_read = Path::new("new.txt");
let stdout_handle = Handle::stdout()?;
let handle = Handle::from_path(path_to_read)?;
if stdout_handle == handle {
return Err(Error::new(
ErrorKind::Other,
"You are reading and writing to the same file",
));
} else {
let file = File::open(&path_to_read)?;
let file = BufReader::new(file);
for (num, line) in file.lines().enumerate() {
println!("{} : {}", num, line?.to_uppercase());
}
}
Ok(())
}
使用内存映射随机访问文件
使用 memmap 创建文件的内存映射,并模拟文件的一些非序列读取。使用内存映射意味着您仅需索引一个切片,而不是使用 seek 方法来导航整个文件。
map::map 函数假定内存映射后的文件没有被另一个进程同时更改,否则会出现竞态条件。
use memmap::Mmap;
use std::fs::File;
use std::io::{Write, Error};
fn main() -> Result<(), Error> {
write!(File::create("content.txt")?, "My hovercraft is full of eels!")?;
let file = File::open("content.txt")?;
let map = unsafe { Mmap::map(&file)? };
let random_indexes = [0, 1, 2, 19, 22, 10, 11, 29];
assert_eq!(&map[3..13], b"hovercraft");
let random_bytes: Vec<u8> = random_indexes.iter()
.map(|&idx| map[idx])
.collect();
assert_eq!(&random_bytes[..], b"My loaf!");
Ok(())
}
更多实践实例请点击底部“阅读原文”,或者访问 https://rust-cookbook.budshome.com,按照左侧导航阅读。
以上实例代码都是完整的、可独立运行的程序,因此你可以直接复制它们到自己的项目中进行试验。
如果希望从头了解如何运行上述实例代码,请参考《Rust 实践指南》中关于本书-如何使用本书实例部分。也可以复制链接:http://budshome.com/rust-cookbook/about.html
边栏推荐
- [cloud resident co creation] Huawei iconnect enables IOT terminals to connect at one touch
- 基于SSH的网上商城设计
- Post MSF infiltration summary
- DeFi借贷协议机制对比:Euler、Compound、Aave和Rari Capital
- Taishan Office Technology Lecture: how to align and draw words of different sizes on the same line
- 漏洞复现----38、ThinkPHP5 5.0.23 远程代码执行漏洞
- 清华只能排第3?2022软科中国大学AI专业排名发布
- 【义修换届大礼包】
- MIT科技评论2022年35岁以下创新者名单发布,含AlphaFold作者等
- Simulation of campus network design based on ENSP
猜你喜欢

Small Tools(3) 集成Knife4j3.0.3接口文档

助力极致体验,火山引擎边缘计算最佳实践

Inventory in the first half of 2022: summary of major updates and technical points of 20+ mainstream databases

Add code block in word (Reprint)

How to solve the lock-in read-only alarm of AutoCAD Chinese language?
![[PROJECT] Xiaomao school (IX)](/img/01/f7fc609e7a156d6e60ce6482ba2ac1.jpg)
[PROJECT] Xiaomao school (IX)

Helping the ultimate experience, best practice of volcano engine edge computing

Small tools (3) integration knife4j3.0.3 interface document

Daily interview 1 question - how to prevent CDN protection from being bypassed

What will be the game changes brought about by the meta universe?
随机推荐
Vscode status bar statusbar
[software testing] basic knowledge of software testing you need to know
Apache 解析漏洞(CVE-2017-15715)_漏洞复现
C语言结构体
New research of HKUST & MsrA: about image to image conversion, finishing is all you need
MSF后渗透总结
Customer relationship CRM management system based on SSH
Deep understanding of JVM (IV) - garbage collection (I)
Synchronized summary
Vue3 reactive database
autocad中文语言锁定只读警报怎么解决?
Only black-and-white box test is required for test opening post? No, but also learn performance test
每日面试1题-如何防止CDN防护被绕过
How to solve the lock-in read-only alarm of AutoCAD Chinese language?
Post penetration file system + uploading and downloading files
One script of unity actual combat realizes radar chart
每日面试1题-蓝队基础面试题-应急响应(1)应急响应基本思路流程+Windows入侵排查思路
IEEE TBD SCI impact factor increased to 4.271, ranking Q1!
[sword finger offer] 53 - I. find the number I in the sorted array
剑指 Offer 17. 打印从1到最大的n位数