Rust- File

2023-10-26

In Rust, file I/O is handled primarily through the std::fs and std::io modules. The std::fs module contains several functions for manipulating the filesystem, such as creating, removing, and reading files and directories. The std::io module contains traits, structs, and enums that can be used to handle input/output in a more abstract way, and is also used for error handling.

Here are a few examples of file operations in Rust:

1. Reading a File

use std::fs::File;
use std::io::Read;

fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    println!("{}", contents);
    Ok(())
}

This program opens the file foo.txt, reads its contents into a string, and then prints the string.

Note: The ? operator in Rust is used for error handling. It’s a shorthand way to propagate errors up the call stack.

When you call a function that returns a Result type, it will return either an Ok(T) variant which contains the successful result, or an Err(E) variant which contains the error information.

If you use the ? operator on a Result value, it has the effect of “unwrapping” the Result if it’s the Ok(T) variant and returning the contained value. However, if the Result is an Err(E) variant, the function will immediately return this Err from the current function.

In the line let mut file = File::open("foo.txt")?;, File::open("foo.txt") returns a Result<File>. If the file is opened successfully, ? unwraps the Result and file gets the File object. If there’s an error (e.g., the file does not exist, or the program doesn’t have permission to access it), the ? operator returns early from the function and gives the error.

The ? operator can only be used in functions that return a Result (or Option), because when an error occurs, ? returns it (it must return the same type as the function). So in the main function, you should specify that it returns a Result. If an error bubbles up to the main function, the error information will be printed to the standard error stream and the program will exit.

fn main() -> std::io::Result<()> {
    let mut file = File::open("foo.txt")?;
    // ...
    Ok(())
}

2. Writing to a File

use std::fs::File;
use std::io::Write;

fn main() -> std::io::Result<()> {
    let mut file = File::create("foo.txt")?;
    file.write_all(b"Hello, world!")?;
    Ok(())
}

This program creates a file named foo.txt, writes the byte string Hello, world! into the file, and then closes the file.

3. Working with Directories

use std::fs;

fn main() -> std::io::Result<()> {
    fs::create_dir("foo_dir")?; // create a directory
    fs::remove_dir("foo_dir")?; // remove the directory
    Ok(())
}

This program creates a directory named foo_dir, then removes it.

All of the functions used in these examples (File::open, File::create, fs::create_dir, etc.) can fail, for example, due to permissions, missing files, etc. They return a Result type, and by returning std::io::Result<()> from main(), these errors will automatically be handled by Rust: it will stop the program and print an error message.

Additionally, Rust has support for reading from and writing to files in a line-by-line or byte-by-byte manner, and includes many other features for advanced file I/O handling. These include file metadata, permissions, and more complex read/write operations.

A comprehensive case is as follows:

use std::fs::{self, OpenOptions};
use std::io::{Write, Read};

fn main() {
    let file = std::fs::File::open("data.txt");
    println!("文件打开\n{:?}", file);

    let file = std::fs::File::create("data2.txt").expect("创建失败");
    println!("文件创建成功{:?}", file);

    fs::remove_file("data.txt").expect("无法删除文件");
    println!("文件已删除");

    let mut file = OpenOptions::new().append(true).open("data2.txt").expect("失败");
    // file.write("\nRust Programming Language".as_bytes()).expect("写入失败");
    // println!("\n数据追加成功");

    file.write_all("Rust".as_bytes()).expect("失败");
    file.write_all("\nRust".as_bytes()).expect("失败");
    println!("\n数据写入成功");
    // // write_all并不会在写入后自动写入换行\n

    let mut file = std::fs::File::open("data2.txt").unwrap();
    let mut contents = String::new();
    file.read_to_string(&mut contents).unwrap();
    println!("{}", contents);
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rust- File 的相关文章

随机推荐

  • Linux驱动框架与LED实战

    目录 驱动框架 相关文件 案例分析 LED驱动框架源码 led class c led class attrs leds class class结构体 led classdev register 某一类的设备创建 led classdev结
  • QT获取显示当前时间和日期

    获取当前时间和日期 QT中获取时间和日期的主要是 QTime QDate 和 QDateTime 这三个类 QTime 类 通过 QTime 类中提供的时间相关的方法 可以获取到当前系统时间 时 分 秒 毫秒 需要注意的是 计时的准确性由底
  • QWidget/QDialog主窗体设置边框圆角

    1 问题 QT中窗体QWidget和QDialog为容器 不能对窗体进行边框圆角样式改变 只能通过绘图QPainter 2 设置无上边框选项窗口 this gt setWindowFlags Qt Widget Qt FramelessWi
  • CSS学习笔记八——宽高自适应

    宽高自适应 一 宽度自适应 二 高度自适应 三 浮动元素的高度自适应 四 窗口自适应 五 结语 一 宽度自适应 不写宽度或者写 width auto就表示宽度自适应 可用于横栏或导航栏 与 width 100 不同 设为100 已经固定了宽
  • MySQL之无限级分类表设计

    首先查找一下goods cates表和table goods brands数据表 分别使用命令 root localhost test gt show columns from goods cates root localhost test
  • 【Spring源码】一:整体流程

    总流程 12 个方法 Prepare this context for refreshing prepareRefresh Tell the subclass to refresh the internal bean factory Con
  • 与焦虑同行,话技术领导者成长

    解码职场焦虑 系列直播第二期来啦 技术领导者在职场跃迁中 会因为各种内外因素的变化而产生焦虑 困惑 烦躁等情绪 我们该怎样与负面情绪共处 认识到局限 接纳并不完美的自己 从而稳步前行 技术Leader成长路上会面对哪些情绪挑战 高压和忙碌状
  • html提取信息变xml,网络爬虫笔记【7】 利用 XPATH 实现 XML 和 HTML 文本信息提取

    XML Extensible Markup Language 指可扩展标记语言 被设计用来传输和存储数据 HTML指的是超文本标记语言 Hyper Text Markup Language 是WWW上用于编写网页的主要工具 详细信息请参考
  • R语言做文本挖掘 Part3文本聚类

    Part3文本聚类 发现有人转载 决定把格式什么重新整理一遍 有时间做个进阶版文本挖掘 恩 原文地址 CSDN R语言做文本挖掘 Part3文本聚类 分类和聚类算法 都是数据挖掘中最常接触到的算法 分类聚类算法分别有很多种 可以看下下面两篇
  • 万字超详细的Java图书管理系统

    生命中的每个人都是一个故事 而每个故事都值得被讲述 作者 不能再留遗憾了 专栏 Java学习 该文章主要内容 用Java实现简单的图书管理系统 文章目录 前言 基本思路 书和书架 书Book类 书架BookList类 用户身份User 父类
  • Oracle : ORA-00001: unique constraint (SHULAN_TEST.SYS_C0026496) violated

    Caused by java lang IllegalStateException Can t overwrite cause with java sql SQLIntegrityConstraintViolationException O
  • Random Vectors and the Variance-Covariance Matrix

    Random Vectors and the Variance Covariance Matrix pdf 多维变量概率论 Definition 1 随机向量 x x 1
  • jsp与html,html与web语言的交互

    jsp 又名java Server Pages 用于开发动态网页 文件扩展名为jsp 优点 1 首先jsp是一种服务端技术 提供了动态接口 用于不断更改数据并调用服务器操作 2 jsp本身是一种编译好的Servlet文件 3 jsp基于ja
  • 给本科实验室的分享PPT续-回复各种问题

    谢邀 该分享主要面向实验室的大一 大二同学
  • Neo4J(Cypher语句)初识

    欢迎各路大神临幸寒舍 以下节点标签为people friend 用户自己也可以设置成其他标签 查询时需要用到标签 这个标签可以类比为关系数据库中的表名 创建节点 关系 创建节点 小明 create n people name 小明 age
  • FFmpeg音频处理——音频混合、拼接、剪切、转码

    接触FFmpeg有一段时间了 它是音视频开发的开源库 几乎其他所有播放器 直播平台都基于FFmpeg进行二次开发 本篇文章来总结下采用FFmpeg进行音频处理 音频混合 音频剪切 音频拼接与音频转码 采用android studio进行开发
  • 一篇搞定React生命周期以及执行顺序 v16.8+(前端面试整理)

    React 组件生命周期 从事前端工作已经有一段时间 最近在面试求职者的时候发现 React最基础的实例生命周期都说不清楚 也不能说清楚每个生命周期方法具体作用 所以我通过代码 官网文档的形式总结下文 React生命周期可以说是react最
  • Ubuntu和windows系统下安装odoo16 社区版和企业版附带安装视频

    Ubuntu安装视频 ubuntu下安装odoo16社区版和企业版 Windows10安装视频 windows10安装odoo16社区版和企业版不成功的看这个视频 还是和以前的类似 先用官方的方法安装社区版 然后企业版源码覆盖掉社区版源码就
  • 数据结构 —— 线索二叉树

    线索二叉树的意义 对于一个有n个节点的二叉树 每个节点有指向左右孩子的指针域 其中会出现n 1个空指针域 这些空间不储存任何事物 浪费着内存的资源 对于一些需要频繁进行二叉树遍历操作的场合 二叉树的非递归遍历操作过程相对比较复杂 递归遍历虽
  • Rust- File

    In Rust file I O is handled primarily through the std fs and std io modules The std fs module contains several functions