e9571_io_lib 0.1.1

A Rust crate for file I/O operations, including line-by-line reading, various write modes, and byte stream reading
Documentation
use std::fs::{File, OpenOptions};
use std::io::{self, BufReader, BufWriter, Read, Write};
use std::path::Path;
use e9571_file_lib::e9571_file_lib::check_file_is_exist;
use std::time::Instant;
use std::collections::HashMap;

pub mod e9571_io_lib {
    use std::fs;
    use std::io::BufRead;
    use super::*;

    /// 逐行读取文件 (Create_Source)
    /// Reads a file line by line and returns a vector of lines
    pub fn create_source(path: &str) -> Result<Vec<String>, io::Error> {
        let mut data_buffer = Vec::new();
        let file = File::open(path)?;
        let mut reader = BufReader::new(file);

        let mut line = String::new();
        while reader.read_line(&mut line)? > 0 {
            data_buffer.push(line.trim().to_string());
            line.clear();
        }
        Ok(data_buffer)
    }

    /// 写入文件 常规写入 (Write_file)
    /// Writes content to a file, appending if it exists, creating otherwise
    pub fn write_file(str: &str, path: &str) -> io::Result<()> {
        let mut file = if check_file_is_exist(path) {
            OpenOptions::new().write(true).append(true).open(path)?
        } else {
            OpenOptions::new().write(true).create(true).open(path)?
        };
        file.write_all(str.as_bytes())?;
        file.sync_all()?;
        Ok(())
    }

    /// 追加写入 (Write_line)
    /// Appends a line to a file with buffering
    pub fn write_line(str: &str, file_path: &str) -> io::Result<()> {
        if !check_file_is_exist(file_path) {
            File::create(file_path)?;
        }
        let file = OpenOptions::new().read(true).write(true).append(true).open(file_path)?;
        let mut writer = BufWriter::new(file);
        writer.write_all(str.as_bytes())?;
        writer.flush()?;
        Ok(())
    }

    /// 文件写入 覆盖模式 (WriteToFile)
    /// Writes content to a file, truncating and creating if needed
    pub fn write_to_file(file_name: &str, content: &str) -> io::Result<()> {
        let mut file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(file_name)?;
        file.write_all(content.as_bytes())?;
        file.sync_all()?;
        Ok(())
    }

    /// 数据写入 精确行 (WriteListtoFile)
    /// Writes a list of strings to a file, one per line
    pub fn write_list_to_file(list: &[String], file_path: &str) -> io::Result<()> {
        let file = File::create(file_path)?;
        let mut writer = BufWriter::new(file);
        for line in list {
            writeln!(writer, "{}", line)?;
        }
        writer.flush()?;
        Ok(())
    }

    /// Map 写入 (WriteMaptoFile)
    /// Writes a map to a file, with key^value per line
    pub fn write_map_to_file(m: &HashMap<String, String>, file_path: &str) -> io::Result<()> {
        let file = File::create(file_path)?;
        let mut writer = BufWriter::new(file);
        for (k, v) in m {
            writeln!(writer, "{}^{}", k, v)?;
        }
        writer.flush()?;
        Ok(())
    }



    /// 读取文件 字节流模式 (ReadAll_Byte)
    /// Reads all bytes from a file opened with append mode
    pub fn read_all_byte(file_path: &str) -> Result<Vec<u8>, io::Error> {
        let mut file = OpenOptions::new().append(true).open(file_path)?;
        let mut buffer = Vec::new();
        file.read_to_end(&mut buffer)?;
        Ok(buffer)
    }

    /// 读取文件 字节流模式 (ReadAll_Byte_Linux)
    /// Reads all bytes from a file directly
    pub fn read_all_byte_linux(file_path: &str) -> Result<Vec<u8>, io::Error> {
        fs::read(file_path)
    }

    /// 文件读取 缓存模式 适用于超大文件 (ReadBlock)
    /// Reads a file in blocks, concatenating and timing the operation
    pub fn read_block(file_path: &str) -> String {
        let start = Instant::now();
        let mut note = String::new();
        let mut count = 0;

        let file = match File::open(file_path) {
            Ok(file) => file,
            Err(e) => {
                println!("{}", e);
                return String::new();
            }
        };
        let mut reader = BufReader::new(file);
        let mut buffer = vec![0; 20_480]; // 20,480 bytes as in Go example

        loop {
            match reader.read(&mut buffer) {
                Ok(n) if n > 0 => {
                    note.push_str(&String::from_utf8_lossy(&buffer[..n]));
                    count += 1;
                }
                Ok(_) => break, // n == 0 indicates EOF
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => {
                    println!("{}", e);
                    break;
                }
            }
        }

        println!("readBlock spend: {:?}", start.elapsed());
        note
    }

    /// 文件路径标准化 (Path_standard)
    /// Replaces backslashes with forward slashes
    pub fn path_standard(path: &str) -> String {
        path.replace("\\", "/")
    }
}