vieyahn2017 / goto

GO C C++ Rust
0 stars 1 forks source link

【Rust】Rust的文件操作 #17

Open vieyahn2017 opened 8 months ago

vieyahn2017 commented 8 months ago

来自 https://www.cnblogs.com/guo-shou/articles/17204639.html

vieyahn2017 commented 8 months ago

use std::io;
use std::io::prelude::*;
use std::fs::File;
use std::io::SeekFrom;

use std::io::Read;
use std::fs::read_to_string;
use std::io::{BufRead, BufReader};
use std::io::Write;
use std::fs::OpenOptions;

fn main() {
}

// cargo test -- --show-output
#[test]
fn test_f1() {
    // let content: String = read_to_string("D:\\yh\\rust\\greeting\\src\\foo").unwrap();
    // foo要放在cargo那层,而不是src这层,否则只能那样全路径读取
    let content: String = read_to_string("foo").unwrap();
    print!("{}", content);
}

#[test]
fn test_f2() {
    let mut f = File::open("foo").unwrap();
    let mut buf: [u8;32] = [0u8; 32];
    // 将文件内容以字节的形式读入到数组中,返回读取的字节数
    while let Ok(len) = File::read(&mut f, &mut buf) {
        // 读取到文件尾时返回0,结束循环
        if len <= 0 {
            break;
        }
        // Note:文件内容由多字节组成,可能会没有完整读入数组
        print!("{}", String::from_utf8_lossy(&buf[0..len]));
    }
}

#[test]
fn test_f3() {
    let mut file: File = File::open("foo").unwrap();
    let mut reader: BufReader<File> = BufReader::new(file);
    // 向缓冲区写入数据
    let buf: &[u8] = reader.fill_buf().unwrap();
    println!("{}", String::from_utf8_lossy(&buf));
    // 按行读取
    for line in reader.lines() {          
        println!("{}", line.unwrap());
    }
}

#[test]
fn test_f4() {
    let content: &str = "123 Hello, world";
    // 以只写的方式打开文件,文件存在则会覆盖原始内容
    let mut file: File = File::create("foo").unwrap();
    // 以字节的形式写入,返回写入的字节数
    let len: usize = file.write(content.as_bytes()).unwrap();
}

// #[test]
// 这个没成功,是后面的write没对,前面的open是成功了的
fn test_f5() {
    let mut file: File = OpenOptions::new()
    .read(true)
    .append(true)       // 以附加的方式在文件尾写入
    .open("foo")
    .unwrap();
    let mut content: String = String::new();
    // 将文件内容读取到字符串中,返回读入的长度
    let len: usize = file.read_to_string(&mut content).unwrap();
    println!("{}", content);
    // 将字符串转变为大写形式后写入
    file.write(content.to_uppercase().as_bytes()).unwrap();
}
vieyahn2017 commented 8 months ago

use std::io;
use std::io::prelude::*;
use std::fs::File;
use std::io::SeekFrom;

use std::io::Read;
use std::fs::read_to_string;
use std::io::{BufRead, BufReader};
use std::io::Write;
use std::fs::OpenOptions;

// 提取函数遇到报错
// error[E0596]: cannot borrow data in a `&` reference as mutable
fn show_file_content(file: &mut File) {
    let mut buf: [u8;32] = [0u8; 32];
    // 将文件内容以字节的形式读入到数组中,返回读取的字节数
    while let Ok(len) = File::read(file, &mut buf) {
        // 读取到文件尾时返回0,结束循环
        if len <= 0 {
            break;
        }
        // Note:文件内容由多字节组成,可能会没有完整读入数组
        print!("{}", String::from_utf8_lossy(&buf[0..len]));
    }
}   

fn main() -> io::Result<()> {
    // let mut f = File::open("foo")?;

    let mut f: File = OpenOptions::new()
    .read(true)
    .append(true)
    .open("foo")
    .unwrap();

    f.seek(SeekFrom::Current(3))?; // A
    // f.rewind()?; // B // 这个是重定向到文件头
    // f.seek(SeekFrom::Start(3))?; // C
    // f.seek(SeekFrom::End(0))?; // D

    show_file_content(&mut f);

    // how to
    f.write_all(b"456")?;

    Ok(())
}