Rust- File

chatgpt/2023/9/27 7:16:13

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 directoryfs::remove_dir("foo_dir")?; // remove the directoryOk(())
}

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并不会在写入后自动写入换行\nlet mut file = std::fs::File::open("data2.txt").unwrap();let mut contents = String::new();file.read_to_string(&mut contents).unwrap();println!("{}", contents);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.exyb.cn/news/show-5313094.html

如若内容造成侵权/违法违规/事实不符,请联系郑州代理记账网进行投诉反馈,一经查实,立即删除!

相关文章

通过标准库创建线程池

线程池提高利用线程效率的原因 线程池可以提高我们利用线程的效率&#xff0c;比通过系统频繁的进行线程的创建和销毁要快很多 我们可以在线程池中先创建好多个线程&#xff0c;当要进行使用的时候从线程池中取出来使用&#xff0c;使用完毕放回线程池中以待下次使用 为什么我们…

【GreenDao】 实现数据库迁移,使用 GreenDao 提供的 MigrationHelper类辅助完成

使用官方提供的greendao-upgradelib 如果你想使用 GreenDaoUpgradeHelper 类来实现 GreenDao 数据库的升级&#xff0c;你可以按照以下步骤进行操作&#xff1a; 首先&#xff0c;添加 GreenDaoUpgradeHelper 的依赖到你的项目中。你可以在项目的 build.gradle 文件中的 depe…

Array.from()方法之什么是类数组对象

Array.from()方法就是将一个类数组对象或者可遍历对象转换成一个真正的数组。 那么什么是类数组对象呢&#xff1f;所谓类数组对象&#xff0c;最基本的要求就是具有length属性的对象。 1、将类数组对象转换为真正数组&#xff1a; let arrayLike {0: tom, 1: 65,2: 男,3: […

虚拟网卡veth 问题 不通 ssh超时 无法 ping通 宿主机 虚拟机

NAT模式下开启veth网络不可用 问题背景: 测试Linux namespace的网络空间 虚拟网卡 veth的隔离性. 我的虚拟机是vmvare,网络模式是NAT,虚拟机OS是centos7 主要动作 创建网络空间 创建虚拟网卡 配置IP 启动成对的虚拟网卡和空间内的lo回环网卡 现象 使用NAT模式下,一旦…

leetcode 面试题 08.05.递归乘法

⭐️ 题目描述 &#x1f31f; leetcode链接&#xff1a;面试题 08.05.递归乘法 思路&#xff1a; A 3 , B 4 &#xff0c;3 * 4 等价于 3 3 3 3。 代码&#xff1a; int multiply(int A, int B){if (!B) {return 0;}return A multiply(A , B - 1); }

【Axure高保真原型】标准金额格式输入框

今天和大家分享标准金额格式输入框的原型模板&#xff0c;在输入框里输入数字后&#xff0c;会自动将对应的数字转为标准金额格式输入&#xff0c;自动添加千分位&#xff0c;例如输入2000&#xff0c;输入内容为2,000.00。具体效果可以观看下方视频或者打开预览地址体验 【原…

【已解决】span的宽度与高度如何设置

本博文源于笔者基础不扎实的情况下遇到的一个问题&#xff0c;问题是我有三个span&#xff0c;想让它们宽度与高度再大点&#xff0c;结果发现怎样设置都设置不了。最后不经意间解决问题 文章目录 1、问题再现2、解决方案3、解决效果 1、问题再现 <span>1</span>…

Android Studio 启用设备远程调试配置完整步聚

启用手机设置->开发者选项-无线调试,然后选择允许 已启用后无线调试变成绿色 ,点击无线调试进入详情页面 点击Android Studio的Device Manager 下的WIFI图标 会弹出下图窗口 打开手机的开发者选项中的WIFI调试(无线调试)下的使用二维码配对设备进行扫描. 设备配对成功后手机…
推荐文章