user15802944
user15802944

Reputation:

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

So how can I copy the terminal output and tell a program to save the output to the file? The function below generates the file and make an output as terminal. What I want to do is to save this terminal output to the file, how can I do this? Is there a better way of doing it?

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)
}

Upvotes: 1

Views: 492

Answers (1)

mcilloni
mcilloni

Reputation: 743

The write!() macro can write on any type, as long as it implements std::io::Write. Just open a std::fs::File in write mode and write!() to it instead of stdout.

Upvotes: 1

Related Questions