Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best variant for appending a new line in a text file?

Tags:

file-io

rust

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

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".

like image 405
Aleksandr Avatar asked Jun 06 '15 15:06

Aleksandr


People also ask

Which function is used to append text to a text file?

PHP Append to File - fwrite() The PHP fwrite() function is used to write and append data into file. fwrite($fp, ' this is additional text ');

How do I append a text file to another text file?

You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.

How do you add a new line to a text file in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.


1 Answers

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

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

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.

like image 91
Shepmaster Avatar answered Sep 25 '22 01:09

Shepmaster