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

我们需要某种方法从文件系统中实际获取数据,以便处理它,并在完成后将其写回来

rust 复制代码
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问题的标准库类型。

rust 复制代码
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,它所做的正是它所说的:它在字符串中搜索正则表达式的所有匹配项,并用给定的替换字符串替换每个匹配项。我们可以把这个逻辑放到一个函数中:

rust 复制代码
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())
  }
rust 复制代码
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);
	} };
}
rust 复制代码
$ echo "Hello, world" > test.txt
$ cargo run "world" "Rust" test.txt test-modified.txt
$ cat test-modified.txt 
Hello, Rust
相关推荐
gbase_lmax18 分钟前
druid连接gbase8s数据库报错空指针
数据库
知知之之23 分钟前
ShardingSphere事务
数据库·mysql
计算机学姐31 分钟前
基于python+django+vue的社区爱心养老管理系统
开发语言·vue.js·后端·python·mysql·django·web3.py
计算机科研之友(Friend)1 小时前
计算机视觉(一)—— 特刊推荐
数据库·人工智能·计算机网络·搜索引擎·计算机视觉
NineData1 小时前
K1计划100%收购 MariaDB; TDSQL成为腾讯云核心战略产品; Oracle@AWS/Google/Azure发布
数据库·oracle·腾讯云·mariadb·azure·amazon·tdsql
金牌服务刘1 小时前
如何选择合适的数据报表工具?
数据库·微服务·信息可视化·容器·数据挖掘·数据分析·负载均衡
一个风轻云淡1 小时前
TDSQL数据库介绍
数据库
丁总学Java2 小时前
mysql-搭建主从复制
数据库·mysql·adb
程序者王大川4 小时前
【物联网】时序数据库InfluxDB解析及1.x版本与2.x版本区别详解
java·数据库·物联网·数据采集·时序数据库·数据·工业互联网平台
我的K84094 小时前
ClickHouse的安装配置+DBeaver远程连接
数据库·clickhouse