当前位置:网站首页>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
边栏推荐
- What did Tongji and Ali study in the CVPR 2022 best student thesis award? This is an interpretation of yizuo
- Tensorflow2 ten must know for deep learning
- Hcip (Huawei Senior Network Security Engineer) (Experiment 8) (MPLS basic experiment)
- 又一篇CVPR 2022论文被指抄袭,平安保险研究者控诉IBM苏黎世团队
- Partition marble (multiple knapsack + binary optimization)
- Development and construction of NFT mining tour gamefi chain tour system
- Do you write API documents or code first?
- Flink series: checkpoint tuning
- 助力极致体验,火山引擎边缘计算最佳实践
- vue3 响应式数据库—— reactive
猜你喜欢

Redis (IX) - enterprise level solution (II)

Deep understanding of JVM (VI) -- garbage collection (III)

News management system based on SSM

Rainbow Brackets 插件的快捷键

漏洞复现----38、ThinkPHP5 5.0.23 远程代码执行漏洞

ABAP publish restful service

Deep understanding of JVM (V) - garbage collection (II)

程序员女友给我做了一个疲劳驾驶检测

Redis (V) - advanced data types

Add code block in word (Reprint)
随机推荐
剑指 Offer 16. 数值的整数次方
每日面试1题-蓝队基础面试题-应急响应(1)应急响应基本思路流程+Windows入侵排查思路
100 examples of bug records of unity development (the first example) -- shader failure or bug after packaging
Advanced customization of uni app [day13]
Tensorflow2 ten must know for deep learning
Animesr: learnable degradation operator and new real world animation VSR dataset
Mo Tianlun salon | Tsinghua qiaojialin: Apache iotdb, originated from Tsinghua, is building an open source ecological road
Do fresh students get a job or choose a job after graduation?
TCP session hijacking based on hunt1.5
Redis (VII) - sentry
Redis (II) -- persistence
How to solve the lock-in read-only alarm of AutoCAD Chinese language?
What did Tongji and Ali study in the CVPR 2022 best student thesis award? This is an interpretation of yizuo
Nielseniq welcomes dawn E. Norvell, head of retail lab, to accelerate the expansion of global retail strategy
DeFi借贷协议机制对比:Euler、Compound、Aave和Rari Capital
Redis (I) - data type
Solve the problem of unable to connect to command metric stream and related problems in the hystrix dashboard
Helping the ultimate experience, best practice of volcano engine edge computing
Switching routing (VLAN) experiment
Development details of NFT casting trading platform