如何复制终端输出并将其放入文件中?

How to copy a terminal output and put it into the file?

那么如何复制终端输出并告诉程序将输出保存到文件中呢?下面的函数生成文件并将输出作为终端。我想做的是将这个终端输出保存到文件中,我该怎么做?有更好的方法吗?

pub fn newsfv<'a, F, C>(files: F, config: C) -> Result<bool, IoError>
where
    F: IntoIterator<Item = &'a Path>,
    C: Into<Option<Config>>,
{
    // get a default config if none provided.
    let mut cfg: Config = config.into().unwrap_or_default();
    // collect the files
    let files: Vec<&Path> = files.into_iter().collect();
    // generate the headers from the files that where found
    write!(
        cfg.stdout,
        "; Generated by dash_hash. All issues report to the Codeberg. Made with <3 by Cerda. https://codeberg.org/CerdaCodes/DashHash/issues"
    )?;
    write!(cfg.stdout, ";\n")?;
    for file in files.iter().filter(|p| p.is_file()) {
        if let Ok(metadata) = std::fs::metadata(file) {
            let mtime: DateTime<Local> = From::from(metadata.modified().unwrap());
            write!(
                cfg.stdout,
                "; {:>12}  {:02}:{:02}.{:02} {:04}-{:02}-{:02} {}\n",
                metadata.len(),
                mtime.hour(),
                mtime.minute(),
                mtime.second(),
                mtime.year(),
                mtime.month(),
                mtime.day(),
                file.display()
            )?;
        }
    }
    // gen sfv file
    let mut success = true;
    for file in &files {
        match compute_crc32(file) {
            Ok(crc32) if cfg.print_basename => {
                let name = file.file_name().unwrap();
                write!(
                    cfg.stdout,
                    "{} {:08X}\n",
                    AsRef::<Path>::as_ref(&name).display(),
                    crc32
                )?
            }
            Ok(crc32) => write!(cfg.stdout, "{} {:08X}\n", file.display(), crc32)?,
            Err(err) => {
                success = false;
                write!(cfg.stderr, "dashHash: {}: {}\n", file.display(), err)?
            }
        }
    }
    // return `true` if all CRC32 where successfully computed
    Ok(success)
}

write!() 宏可以写在任何类型上,只要它实现了 std::io::Write。只需在写入模式下打开 std::fs::File 并向其写入!() 而不是 stdout.