SoFunction
Updated on 2025-04-09

How to access .ini format configuration files in Rust app

Rust access .ini format configuration files

Accessing .ini format configuration files in Rust apps, you can use third-party libraries, such asiniorconfig. Below is a useiniExample of a library that allows you to read and parse .ini files.

Using the ini library

  1. Add dependencies

First, you need toAdd to the fileiniLibrary dependencies:

[dependencies]
ini = "0.17"  # Please check the latest version number
  1. Read and parse .ini files

You can then read and parse the .ini file in your Rust code. Here is a simple example:

use ini::Ini;
use std::fs::File;
use std::io::Read;
use std::path::Path;

fn main() {
    // Define the configuration file path    let path = Path::new("");
    let display = ();

    // Open the configuration file    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, why),
        Ok(file) => file,
    };

    // Read file content    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Err(why) => panic!("couldn't read {}: {}", display, why),
        Ok(_) => println!("File contents: {}", contents),
    };

    // parse .ini file    let ini = Ini::load_from_str(&contents).unwrap_or_else(|err| {
        panic!("Failed to parse config file: {}", err);
    });

    // Access configuration values    if let Some(section) = (Some("database")) {
        let db_url = ("url").unwrap_or("not_found");
        let db_user = ("user").unwrap_or("not_found");
        println!("Database URL: {}", db_url);
        println!("Database User: {}", db_user);
    } else {
        println!("No [database] section found in config file.");
    }
}

Example.ini file ()

[database]
url = "postgresql://user:password@localhost:5432/mydatabase"
user = "admin"

Run the program

Make sure yoursThe file and the executable are in the same directory, and then run your Rust program:

cargo run

explain

  1. Add dependencies:existAdded ininilibrary dependencies.
  2. Open the file:usestd::fs::FileOpen the configuration file.
  3. Read file content: Read the file content into a string.
  4. parse .ini files:useini::IniParses string content.
  5. Access configuration values:passsectionandgetMethod access configuration values.

Things to note

  • Make sure you use itiniThe library version is compatible with the sample code.
  • The configuration file path and name should match your project structure.
  • Error handling: used in the sample codepanic!To perform error handling, you may need a more robust error handling mechanism in actual projects.

This way, you can easily access and parse .ini format configuration files in the Rust application.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.