Skip to content

Instantly share code, notes, and snippets.

@crumblingstatue
Created February 11, 2016 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crumblingstatue/13393f252e42038190f9 to your computer and use it in GitHub Desktop.
Save crumblingstatue/13393f252e42038190f9 to your computer and use it in GitHub Desktop.
use std::fs::File;
use std::io::prelude::*;
fn main() {
let text = {
let mut f = File::open("test.txt").unwrap();
let mut buf = String::new();
f.read_to_string(&mut buf).unwrap();
buf
};
let text_to_insert_before = "Insert before me please!";
let text_to_insert = "I am an inserted line.\n";
let index = text.find(text_to_insert_before).expect("Could not find replacement guide.");
let mut new_text = String::with_capacity(text.len() + text_to_insert.len());
new_text.push_str(&text[..index]);
new_text.push_str(text_to_insert);
new_text.push_str(&text[index..]);
let mut f = File::create("test.txt").unwrap();
f.write_all(new_text.as_bytes()).unwrap();
}
I contain some text.
Insert before me please!
Thanks!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment