当前位置:网站首页>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
边栏推荐
- 每日面试1题-如何防止CDN防护被绕过
- Flutter custom component
- 元宇宙带来的游戏变革会是怎样的?
- MySQL advanced - Architecture
- 剑指 Offer 16. 数值的整数次方
- MIT science and Technology Review released the list of innovators under the age of 35 in 2022, including alphafold authors, etc
- Force deduction solution summary 1175- prime number arrangement
- 先写API文档还是先写代码?
- Add code block in word (Reprint)
- 【二叉树】前序遍历构造二叉搜索树
猜你喜欢

Volcano engine was selected into the first "panorama of edge computing industry" in China

Talk about the SQL server version of DTM sub transaction barrier function

What did Tongji and Ali study in the CVPR 2022 best student thesis award? This is an interpretation of yizuo

基于eNSP的校园网设计的仿真模拟

Redis (I) - data type

Redis (VI) - master-slave replication

剑指 Offer 17. 打印从1到最大的n位数

Research on the principle of Tencent persistence framework mmkv

Rainbow Brackets 插件的快捷键

MIT science and Technology Review released the list of innovators under the age of 35 in 2022, including alphafold authors, etc
随机推荐
It's not easy to say I love you | use the minimum web API to upload files
Post MSF infiltration summary
Post penetration file system + uploading and downloading files
IEEE TBD SCI impact factor increased to 4.271, ranking Q1!
MIT science and Technology Review released the list of innovators under the age of 35 in 2022, including alphafold authors, etc
漏洞复现----35、uWSGI PHP 目录遍历漏洞 (CVE-2018-7490)
基于eNSP的校园网设计的仿真模拟
【机器学习】K-means聚类分析
联想“双平台”运维解决方案 助力智慧医疗行业智慧管理能力全面提升
The new Post-00 Software Test Engineer in 2022 is a champion
uni-app进阶之自定义【day13】
Redis (IV) - delete policy
Lenovo's "dual platform" operation and maintenance solution helps to comprehensively improve the intelligent management ability of the intelligent medical industry
What will be the game changes brought about by the meta universe?
Synchronized summary
How to solve the lock-in read-only alarm of AutoCAD Chinese language?
Deep understanding of JVM (IV) - garbage collection (I)
In distributed scenarios, do you know how to generate unique IDs?
Ardunio esp32 obtains real-time temperature and humidity in mqtt protocol (DH11)
Redis (V) - advanced data types