在文本文件中添加新行的最佳变体是什么? [英] What is the best variant for appending a new line in a text file?

查看:67
本文介绍了在文本文件中添加新行的最佳变体是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在文件末尾添加新行:

I am using this code to append a new line to the end of a file:

let text = "New line".to_string();

let mut option = OpenOptions::new();
option.read(true);
option.write(true);
option.create(true);

match option.open("foo.txt") {
    Err(e) => {
        println!("Error");
    }
    Ok(mut f) => {
        println!("File opened");
        let size = f.seek(SeekFrom::End(0)).unwrap();
        let n_text = match size {
            0 => text.clone(),
            _ => format!("\n{}", text),
        };
        match f.write_all(n_text.as_bytes()) {
            Err(e) => {
                println!("Write error");
            }
            Ok(_) => {
                println!("Write success");
            }
        }

        f.sync_all();
    }
}

它有效,但是我认为这太困难了.我找到了option.append(true);,但是如果我用它代替option.write(true);,则会出现写入错误".

It works, but I think it's too difficult. I found option.append(true);, but if I use it instead of option.write(true); I get "Write error".

推荐答案

使用 OpenOptions::append 是追加到文件的最清晰方法:

Using OpenOptions::append is the clearest way to append to a file:

use std::fs::OpenOptions;
use std::io::prelude::*;

fn main() {
    let mut file = OpenOptions::new()
        .write(true)
        .append(true)
        .open("my-file")
        .unwrap();

    if let Err(e) = writeln!(file, "A new line!") {
        eprintln!("Couldn't write to file: {}", e);
    }
}

从Rust 1.8.0开始( commit )和 RFC 1252 append(true)表示write(true).这应该不再是问题了.

As of Rust 1.8.0 (commit) and RFC 1252, append(true) implies write(true). This should not be a problem anymore.

在Rust 1.8.0之前,您必须同时使用 writeappend —第一个允许您将字节写入文件,第二个允许将字节写入位置.

Before Rust 1.8.0, you must use both write and append — the first one allows you to write bytes into a file, the second specifies where the bytes will be written.

这篇关于在文本文件中添加新行的最佳变体是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆