当前位置:网站首页>File reading and writing for rust file system processing - rust Practice Guide
File reading and writing for rust file system processing - rust Practice Guide
2022-06-30 23:57:00 【ruonou. com】
Rust in , File read / write processing is simple and efficient . The code is also very compact , Easy to read . We read the character serial from the file 、 Avoid reading and writing to the same file 、 Use memory mapped random access files to learn about these three typical cases of file processing .
File processing scenarios are familiar to everyone , So don't talk too much , Look directly at the code .
Read the character serial of the file
We write three lines of information to the file , And then use BufRead::lines Created iterator Lines Read the file , Read back one line at a time .File The module implements to provide BufReader Structure of the Read trait.File::create Open file File To write ,File::open Then read .
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(())
}
Avoid reading and writing the same file in file processing
Use... For files same_file::Handle Structure , You can test whether file handles are equivalent . In this example , The file handles to be read and written will be tested for equality .
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(())
}
Random access to files using memory mapping
Use memmap Create a memory map for the file , And simulate some non sequential reading of files . Using memory mapping means that you only need to index one slice , Instead of using seek Method to navigate the entire file .
map::map The function assumes that the memory mapped file has not been changed by another process at the same time , Otherwise, race conditions will occur .
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(())
}
For more practical examples, please click on the bottom “ Read the original ”, Or visit https://rust-cookbook.budshome.com, Follow the left navigation to read .
The above example code is complete 、 A program that can run independently , So you can copy them directly into your own project for testing .
If you want to know how to run the above example code from scratch , Please refer to 《Rust Practice Guide 》 About this book - How to use examples in this book part . You can also copy Links :http://budshome.com/rust-cookbook/about.html
边栏推荐
- Explain kubernetes backup and recovery tools velero | learn more about carina series phase III
- Don't worry about whether you can be a coder if you don't learn English well. Learn it first
- Is it safe to choose mobile phone for stock trading account opening in Hangzhou?
- Kubevela 1.4: make application delivery safer, easier to use, and more transparent
- Development of wireless U-shaped ultrasonic electric toothbrush
- PS2 handle-1 "recommended collection"
- What does project management really manage?
- Cesiumjs 2022 ^ source code interpretation [6] - new architecture of modelempirical
- Arthas debugging problem determination Toolkit
- ABAQUS 2022 latest edition - perfect realistic simulation solution
猜你喜欢

In depth understanding of jetpack compose kernel: slottable system

Zero sample and small sample learning

1. crawler's beautifulsoup parsing library & online parsing image verification code
![Cesiumjs 2022 ^ source code interpretation [6] - new architecture of modelempirical](/img/ce/519778cd731f814ad111d1e37abd10.png)
Cesiumjs 2022 ^ source code interpretation [6] - new architecture of modelempirical

Shell multitasking to download video at the same time

深入理解 Jetpack Compose 内核:SlotTable 系统

未来十年世界数字化与机器智能展望

76 page comprehensive solution 2022 for smart Logistics Park (download attached)

Makefile notes (Yiwen Institute makefile)

In 2022, the latest JCR officially released the list of the latest global impact factors (top 600)
随机推荐
深入理解 Jetpack Compose 内核:SlotTable 系统
Reason why wechat payment wxpaypubhelper V3 callback XML is empty
206 page Shanghai BIM Technology Application and development report 2021
JMeter cross thread parameter association requires no script
Fh6908a negative pole turn off synchronous rectification analog low voltage drop diode control IC chip tsot23-6 ultra low power rectifier 1W power consumption < 100ua static replacement mp6908
MaxPool2d详解--在数组和图像中的应用
Zero sample and small sample learning
女朋友说:你要搞懂了MySQL三大日志,我就让你嘿嘿嘿!
Code de conduite pour la vente de fonds et la gestion de l'information
The programmer's girlfriend gave me a fatigue driving test
35家巨头科技公司联合组成元宇宙标准论坛组织
一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图
Vmware16 installing win11 virtual machine (the most complete step + stepping on the pit)
6-1 exploit -ftp exploit
Random ball size, random motion collision
网上开华泰证券的股票账户是否安全呢?
[NLP] [textcnn] text classification
Why should VR panoramic shooting join us? Leverage resources to achieve win-win results
CTFSHOW框架复现篇
Ctfshow permission maintenance