Rust: Reading and Writing Files

2024-08-28 03:12
文章标签 rust files reading writing

本文主要是介绍Rust: Reading and Writing Files,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Reading and Writing Files

We need some way to actually get data from the filesystem so we can process it, and write it back when we’re done
我们需要某种方法从文件系统中实际获取数据,以便处理它,并在完成后将其写回来

use std::fs;

std::fs::read_to_string returns a Result<String, std::io::Error>.
If the function succeeds, it produces a String. If it fails, it produces a std::io::Error, the standard library’s type for representing I/O problems.
std::fs::read_to_string返回Result<String, std::io::Error>。
如果函数成功,它将生成一个String。如果失败,它会产生std::io::Error,这是表示I/O问题的标准库类型。

fn main() {let args = parse_args();let data = match fs::read_to_string(&args.filename) { Ok(v) => v,Err(e) => {eprintln!("{} failed to read from file '{}': {:?}","Error:".red().bold(), args.filename, e);std::process::exit(1);} };match fs::write(&args.output, &data) { Ok(_) => {},Err(e) => {eprintln!("{} failed to write to file '{}': {:?}","Error:".red().bold(), args.filename, e);std::process::exit(1);} };
}

Find and Replace

The final touch for this program is to implement its actual functionality: finding and replacing. For this, we’ll use the regex crate, which compiles and executes regular expressions. It provides a struct called Regex, which represents a compiled regular expression. Regex has a method replace_all, which does exactly what it says: it searches a string for all matches of the regular expression and replaces each one with a given replacement string. We can pull this logic out into a function:

这个程序的最后一步是实现它的实际功能:查找和替换。为此,我们将使用regex crate,它编译并执行正则表达式。它提供了一个名为Regex的结构体,它表示编译后的正则表达式。Regex有一个方法replace_all,它所做的正是它所说的:它在字符串中搜索正则表达式的所有匹配项,并用给定的替换字符串替换每个匹配项。我们可以把这个逻辑放到一个函数中:

use regex::Regex;
fn replace(target: &str, replacement: &str, text: &str)-> Result<String, regex::Error>{let regex = Regex::new(target)?;Ok(regex.replace_all(text, replacement).to_string())}
fn main() {let args = parse_args();let data = match fs::read_to_string(&args.filename) { Ok(v) => v,Err(e) => {eprintln!("{} failed to read from file '{}': {:?}","Error:".red().bold(), args.filename, e);std::process::exit(1);} };let replaced_data = match replace(&args.target, &args.replacement, &data) {Ok(v) => v,Err(e) => {eprintln!("{} failed to replace text: {:?}","Error:".red().bold(), e);std::process::exit(1);}};match fs::write(&args.output, &replaced_data) { Ok(v) => v,Err(e) => {eprintln!("{} failed to write to file '{}': {:?}","Error:".red().bold(), args.filename, e);std::process::exit(1);} };
}
$ echo "Hello, world" > test.txt
$ cargo run "world" "Rust" test.txt test-modified.txt
$ cat test-modified.txt 
Hello, Rust

这篇关于Rust: Reading and Writing Files的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1113563

相关文章

Rust中的注释使用解读

《Rust中的注释使用解读》本文介绍了Rust中的行注释、块注释和文档注释的使用方法,通过示例展示了如何在实际代码中应用这些注释,以提高代码的可读性和可维护性... 目录Rust 中的注释使用指南1. 行注释示例:行注释2. 块注释示例:块注释3. 文档注释示例:文档注释4. 综合示例总结Rust 中的注释

Rust格式化输出方式总结

《Rust格式化输出方式总结》Rust提供了强大的格式化输出功能,通过std::fmt模块和相关的宏来实现,主要的输出宏包括println!和format!,它们支持多种格式化占位符,如{}、{:?}... 目录Rust格式化输出方式基本的格式化输出格式化占位符Format 特性总结Rust格式化输出方式

Rust中的Drop特性之解读自动化资源清理的魔法

《Rust中的Drop特性之解读自动化资源清理的魔法》Rust通过Drop特性实现了自动清理机制,确保资源在对象超出作用域时自动释放,避免了手动管理资源时可能出现的内存泄漏或双重释放问题,智能指针如B... 目录自动清理机制:Rust 的析构函数提前释放资源:std::mem::drop android的妙

Rust中的BoxT之堆上的数据与递归类型详解

《Rust中的BoxT之堆上的数据与递归类型详解》本文介绍了Rust中的BoxT类型,包括其在堆与栈之间的内存分配,性能优势,以及如何利用BoxT来实现递归类型和处理大小未知类型,通过BoxT,Rus... 目录1. Box<T> 的基础知识1.1 堆与栈的分工1.2 性能优势2.1 递归类型的问题2.2

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

浅析Rust多线程中如何安全的使用变量

《浅析Rust多线程中如何安全的使用变量》这篇文章主要为大家详细介绍了Rust如何在线程的闭包中安全的使用变量,包括共享变量和修改变量,文中的示例代码讲解详细,有需要的小伙伴可以参考下... 目录1. 向线程传递变量2. 多线程共享变量引用3. 多线程中修改变量4. 总结在Rust语言中,一个既引人入胜又可

Rust 数据类型详解

《Rust数据类型详解》本文介绍了Rust编程语言中的标量类型和复合类型,标量类型包括整数、浮点数、布尔和字符,而复合类型则包括元组和数组,标量类型用于表示单个值,具有不同的表示和范围,本文介绍的非... 目录一、标量类型(Scalar Types)1. 整数类型(Integer Types)1.1 整数字

Rust中的Option枚举快速入门教程

《Rust中的Option枚举快速入门教程》Rust中的Option枚举用于表示可能不存在的值,提供了多种方法来处理这些值,避免了空指针异常,文章介绍了Option的定义、常见方法、使用场景以及注意事... 目录引言Option介绍Option的常见方法Option使用场景场景一:函数返回可能不存在的值场景

【Rust练习】12.枚举

练习题来自:https://practice-zh.course.rs/compound-types/enum.html 1 // 修复错误enum Number {Zero,One,Two,}enum Number1 {Zero = 0,One,Two,}// C语言风格的枚举定义enum Number2 {Zero = 0.0,One = 1.0,Two = 2.0,}fn m

linux中使用rust语言在不同进程之间通信

第一种:使用mmap映射相同文件 fn main() {let pid = std::process::id();println!(