Rust 文件

创建文件

目录不存在会报错,所以要提前创建目录。
方式一:通过File创建

use std::fs::{self, File};
use std::io::{self, Write};
use std::path::Path;

// 支持相对路径和绝对路径
// 相对路径是相对于当前 crate 所在的目录
fn create_file(path: &str) -> io::Result<File> {
    let file = File::create(path);
    if file.is_err() {
        if let Some(parent) = Path::new(path).parent() {
            fs::create_dir_all(parent).unwrap();
            return File::create(path);
        }
    }

    file
}

fn main() {
    // let mut file = create_file("D:/hello.txt").unwrap();
    let mut file = create_file("hello.txt").unwrap();
    file.write("Hello World".as_bytes()).unwrap();
}

方式二:通过OpenOptions创建

use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::Path;

// 支持相对路径和绝对路径
// 相对路径是相对于当前 crate 所在的目录
fn create_file(path: &str) -> io::Result<File> {
    let mut open_options = OpenOptions::new();
    open_options.write(true).create(true);

    let file = open_options.open(path);
    if file.is_err() {
        if let Some(parent) = Path::new(path).parent() {
            fs::create_dir_all(parent).unwrap();
            return open_options.open(path);
        }
    }

    file
}

fn main() {
    // let mut file = create_file("D:/hello.txt").unwrap();
    let mut file = create_file("hello.txt").unwrap();
    file.write("Hello World".as_bytes()).unwrap();
}

其实,File::create()用的就是OpenOptions。

#[stable(feature = "rust1", since = "1.0.0")]
pub fn create<P: AsRef<Path>>(path: P) -> io::Result<File> {
    OpenOptions::new().write(true).create(true).truncate(true).open(path.as_ref())
}
删除文件
use std::fs;

fn main() {
    // fs::remove_file("D:/hello.txt").unwrap();
    fs::remove_file("hello.txt").unwrap();
}
打开文件
use std::fs::File;
use std::io::Read;

fn main() {
    // 只读
    let mut file = File::open("hello.txt").unwrap();
    let mut buffer = [0; 1024];
    file.read(&mut buffer).unwrap();
    println!("{}", String::from_utf8(buffer.to_vec()).unwrap());
}
重命名文件
use std::fs;

fn main() {
    // fs::rename("D:/hello.txt", "D:/hi.txt").unwrap();
    fs::rename("hello.txt", "hi.txt").unwrap();
}
追加/覆盖内容
use std::fs::OpenOptions;
use std::io::Write;

fn main() {
    // 向文件追加内容
    let append = true;
    let path = "hello.txt";
    let mut file = OpenOptions::new().write(true).append(append).truncate(!append).open(path).unwrap();
    file.write_all("Hello World".as_bytes()).unwrap();

    // 覆盖文件内容
    let append = false;
    let path = "hello.txt";
    let mut file = OpenOptions::new().write(true).append(append).truncate(!append).open(path).unwrap();
    file.write_all("Hello World".as_bytes()).unwrap();
}
获取文件大小
use std::fs;

fn main() {
    // 获取文件的实际大小,而非硬盘上的大小
    let len = fs::metadata("hello.txt").unwrap().len();
    println!("len: {}", len);
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值