Created
February 11, 2016 11:30
-
-
Save crumblingstatue/13393f252e42038190f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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