Rust - 文件输入&输出

Rust - 文件输入&输出 首页 / Rust入门教程 / Rust - 文件输入&输出

除了对控制台进行读写之外,Rust还允许对文件进行读写,File结构代表一个文件,它允许程序对文件执行读写操作, File结构中的所有方法均返回io::Result枚举的变体。

写入文件

以下程序创建文件" data.txt",create()方法用于创建文件,如果文件创建成功,该方法将返回文件句柄,最后一行 write_all 函数将在新创建的文件中写入字节,如果任何操作失败,则Expect()函数将返回错误消息。
use std::io::Write;
fn main() {
   let mut file=std::fs::File::create("data.txt").expect("create failed");
   file.write_all("Hello Learnfk".as_bytes()).expect("write failed");
   file.write_all("\nLearnFk".as_bytes()).expect("write failed");
   println!("data written to file" );
}
data written to file

从文件读取

以下程序读取data.txt文件中的内容,并将其打印到控制台,"Open"函数用于打开现有文件,文件的绝对或相对路径作为参数传递给open()函数,如果文件不存在或由于某种原因无法访问,则open()函数将引发异常。如果成功,则将此类文件的文件句柄分配给" file"变量。

"File"句柄的" read_to_string"函数用于将该文件的内容读入字符串变量。

use std::io::Read;

fn main(){
   let mut file=std::fs::File::open("data.txt").unwrap();
   let mut contents=String::new();
   file.read_to_string(&mut contents).unwrap();
   print!("{}", contents);
}
Hello Learnfk
LearnFk

删除文件

以下示例使用remove_file()函数删除文件,如果发生错误,expect()函数将返回自定义消息。

无涯教程网

use std::fs;
fn main() {
   fs::remove_file("data.txt").expect("could not remove file");
   println!("file is removed");
}
file is removed

追加数据

append()函数将数据写入文件的末尾,这在下面给出的示例中显示-

链接:https://www.learnfk.comhttps://www.learnfk.com/rust/rust-file-input-output.html

来源:LearnFk无涯教程网

use std::fs::OpenOptions;
use std::io::Write;

fn main() {
   let mut file=OpenOptions::new().append(true).open("data.txt").expect(
      "cannot open file");
   file.write_all("Hello Learnfk".as_bytes()).expect("write failed");
   file.write_all("\nLearnFk".as_bytes()).expect("write failed");
   println!("file append success");
}
file append success

复制文件

以下示例将文件中的内容复制到新文件。

use std::io::Read;
use std::io::Write;

fn main() {
   let mut command_line: std::env::Args=std::env::args();
   command_line.next().unwrap();
   //跳过可执行文件名
   //接受源文件
   let source=command_line.next().unwrap();
   //接受目标文件
   let destination=command_line.next().unwrap();
   let mut file_in=std::fs::File::open(source).unwrap();
   let mut file_out=std::fs::File::create(destination).unwrap();
   let mut buffer=[0u8; 4096];
   loop {
      let nbytes=file_in.read(&mut buffer).unwrap();
      file_out.write(&buffer[..nbytes]).unwrap();
      if nbytes < buffer.len() { break; }
   }
}

以 main.exe data.txt datacopy.txt 执行上述程序,执行文件时传递了两个命令行参数-

  • 源文件的路径
  • 目标存储文件

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

深入浅出gRPC -〔李林锋〕

趣谈Linux操作系统 -〔刘超〕

Python核心技术与实战 -〔景霄〕

编辑训练营 -〔总编室〕

接口测试入门课 -〔陈磊〕

大数据经典论文解读 -〔徐文浩〕

林外 · 专利写作第一课 -〔林外〕

零基础GPT应用入门课 -〔林健(键盘)〕

好记忆不如烂笔头。留下您的足迹吧 :)