Different Types of Files

1. .txt File

.txt is a plain text file that contains human-readable text without any specific structure. It can any kind of textual information. we use a text file to store data, documentation, source code, etc.

Below is the program to implement .txt file:

Rust




use std::io::{self, Write};
use std::fs::File;
 
fn main() -> io::Result<()> {
    let message: String = "geekforgeeks.org".to_string();
 
    let mut file: File = File::create("website.txt")?;
    file.write(message.as_bytes())?;
     
    println!("Message written successfully.");
    Ok(())
}


Output:

2. .json File

JSON (JavaScript Object Notation) is a popular data format with diverse uses in data interchange. json is a text-based format that is language-indpendent and can be read and used as a data format by any programming language.

We use json files to store structured data, configurations, and even objects. json files can be easily parsed (analyzed) and generated by most programming languages, making it a convenient data interchange format.

Below is the program to implement .json file:

Rust




use std::io::{self, Write};
use std::fs::File;
use serde_json::json; // You may need to add `serde_json` as a dependency in your Cargo.toml
 
fn main() -> io::Result<()> {
    // Create an object which we'll save as JSON
    let data = json!({
        "name": "w3wiki",
        "type": "Educational",
        "website": "<https://www.w3wiki.org/>"
    });
 
    let mut file: File = File::create("website.json")?;
    file.write(data.to_string().as_bytes())?;
 
    println!("Data written successfully as JSON.");
    Ok(())
}


Output:

In conclusion, File Input and Output is a very important function of everyday computing life. Rust helps in reading, writing, and deleting files with its inbuilt modules and functions. These tools empower developers to efficiently manage and file interactions in their Rust applications.



File I/O in Rust

File I/O in Rust enables us to read from and write to files on our computer. To write or read or write in a file, we need to import modules (like libraries in C++) that hold the necessary functions. This article focuses on discussing File I/O in Rust.

Similar Reads

Methods for File I/O

Given below are some methods and their syntax for various file I/O operations:...

Examples

Write a File...

Different Types of Files

...