Q:

Rust program to replace a word in a file

belongs to collection: Rust File I/O Programs

0

In this program, we will open a text file and replace the word in the text file and print the appropriate message.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to replace a word in a file is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to replace a word in a file

use std::fs::File;
use std::io::{self, Read, Write};

fn main() {
    // Handle errors
    run().unwrap();
}

fn run() -> Result<(), io::Error> {

    let word_from = "Friends";
    let word_to = "World";
    
    let mut source= File::open("sample.txt")?;
    let mut data1 = String::new();
    
    source.read_to_string(&mut data1)?;
    
    drop(source); 

    let data2 = data1.replace(&*word_from, &*word_to);


    let mut dest = File::create("sample.txt")?;
    dest.write(data2.as_bytes())?;

    println!("World replaced in sample.txt successfully");

    Ok(())
}

Output:

$ cat sample.txt 
Hello Friends
Hello India

$ rustc main.rs

$ ./main
World replaced in sample.txt successfully

$ cat sample.txt 
Hello World
Hello India

Explanation:

In the above program, we created a function run() and main(). The run() is a special type of function, it can handle generated errors. And, we replaced the specific word with another word in a file. In the main() function, we called the run() method and replace a specific word in the file with another word, and printed the appropriate message.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to remove newline characters from the... >>
<< Rust program to read a file line by line...