ADVERTISEMENT
ADVERTISEMENT

Rust program to remove a specified word from the file

Rust | File I/O Example: Write a program to remove a specified word from the file.
Submitted by Nidhi, on November 01, 2021

Problem Solution:

In this program, we will open a text file and remove a specific word from the file and print the appropriate message.

Program/Source Code:

The source code to remove a specified word from the file is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to remove a specified word 
// from 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 = "Hello";
    let word_to = "";
    
    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!("Word 'Hello' removed from sample.txt successfully");

    Ok(())
}

Output:

$ cat sample.txt 
Hello World
Hello India

$ rustc main.rs

$ ./main
Word 'Hello' removed from sample.txt successfully

$ cat sample.txt 
 World
 India

Explanation:

In the above program, we created two functions run() and main(). The run() is a special type of function, it can handle generated errors. And, we removed the word "Hello" from the "sample.txt" file.

In the main() function, we called the run() method and removed the word "Hello" from the "sample.txt" file and printed the appropriate message.

Rust File I/O Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.