当前位置:网站首页>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
边栏推荐
- AnimeSR:可学习的降质算子与新的真实世界动漫VSR数据集
- Lenovo's "dual platform" operation and maintenance solution helps to comprehensively improve the intelligent management ability of the intelligent medical industry
- New research of HKUST & MsrA: about image to image conversion, finishing is all you need
- Tensorflow2 深度学习十必知
- DeFi借贷协议机制对比:Euler、Compound、Aave和Rari Capital
- Daily interview 1 question - how to prevent CDN protection from being bypassed
- Several points in MySQL that are easy to ignore and forget
- Small tools (3) integration knife4j3.0.3 interface document
- Tencent cloud installs MySQL database
- Do fresh students get a job or choose a job after graduation?
猜你喜欢

ASP. Net generate verification code

漏洞复现----37、Apache Unomi 远程代码执行漏洞 (CVE-2020-13942)

火山引擎入选国内首个《边缘计算产业全景图》

It's not easy to say I love you | use the minimum web API to upload files

Another CVPR 2022 paper was accused of plagiarism, and Ping An insurance researchers sued IBM Zurich team

MySQL reports that the column timestamp field cannot be null

Oneortwo bugs in "software testing" are small things, but security vulnerabilities are big things. We must pay attention to them
![[software testing] basic knowledge of software testing you need to know](/img/cf/875f7a2a6f678eef22cd8b9e0f912d.jpg)
[software testing] basic knowledge of software testing you need to know

TCP session hijacking based on hunt1.5

Importing alicloud ECS locally to solve deployment problems
随机推荐
Volcano engine was selected into the first "panorama of edge computing industry" in China
Tensorflow2 ten must know for deep learning
漏洞复现----35、uWSGI PHP 目录遍历漏洞 (CVE-2018-7490)
Elastic 8.0: opening a new era of speed, scale, relevance and simplicity
[BJDCTF2020]The mystery of ip|[CISCN2019 华东南赛区]Web11|SSTI注入
vue3 响应式数据库—— reactive
漏洞复现----37、Apache Unomi 远程代码执行漏洞 (CVE-2020-13942)
MSF后渗透总结
Distributed machine learning: model average Ma and elastic average easgd (pyspark)
Several points in MySQL that are easy to ignore and forget
Flink series: checkpoint tuning
港科大&MSRA新研究:关于图像到图像转换,Finetuning is all you need
Communication network electronic billing system based on SSH
助力极致体验,火山引擎边缘计算最佳实践
大文件处理(上传,下载)思考
Redis (IX) - enterprise level solution (II)
Redis (VI) - master-slave replication
抖音最新Xbogus,signature生成js逆向分析
Importing alicloud ECS locally to solve deployment problems
[sword finger offer] 53 - I. find the number I in the sorted array