当前位置:网站首页>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
边栏推荐
- Shell multitasking to download video at the same time
- 在指南针上买基金安全吗?
- Kubernetes ---- pod configuration container start command
- Wordpress blog uses volcano engine veimagex for static resource CDN acceleration (free)
- Detailed explanation of conv2d of pytorch
- CTFSHOW权限维持篇
- Dataloader source code_ DataLoader
- HP 惠普笔记本电脑 禁用触摸板 在插入鼠标后
- Fund managers' corporate governance and risk management
- 35家巨头科技公司联合组成元宇宙标准论坛组织
猜你喜欢
![Cesiumjs 2022 ^ source code interpretation [6] - new architecture of modelempirical](/img/ce/519778cd731f814ad111d1e37abd10.png)
Cesiumjs 2022 ^ source code interpretation [6] - new architecture of modelempirical

In depth understanding of jetpack compose kernel: slottable system

SSM integration process (integration configuration, function module development, interface test)

When is it appropriate to replace a virtual machine with a virtual machine?

5g smart building solution 2021

Prospects of world digitalization and machine intelligence in the next decade

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

MaxPool2d详解--在数组和图像中的应用

Random ball size, random motion collision

Ride: get picture Base64
随机推荐
基金销售行为规范及信息管理
Prospects of world digitalization and machine intelligence in the next decade
C /platform:anycpu32bitpererrored can only be used with /t:exe, /t:winexe and /t:appcontainerexe
One revolution, two forces and three links: the "carbon reduction" road map behind the industrial energy efficiency improvement action plan
How do I open a stock account on my mobile phone? In addition, is it safe to open a mobile account?
[PHP] self developed framework qphp, used by qphp framework
Kubernetes ---- pod configuration container start command
How to use dataant to monitor Apache APIs IX
IFLYTEK active competition summary! (12)
[designmode] factory pattern
Software engineering best practices - project requirements analysis
Why should VR panoramic shooting join us? Leverage resources to achieve win-win results
Ride: get picture Base64
女朋友说:你要搞懂了MySQL三大日志,我就让你嘿嘿嘿!
composer
Repetition is the mother of skill
Shell multitasking to download video at the same time
How to open a stock account? Is it safe to open a mobile account
E-commerce seckill system
2022-06-30:以下golang代码输出什么?A:0;B:2;C:运行错误。 package main import “fmt“ func main()