Read a file and assign variable with a specific data


#1

Hello there,

I have a .ini file with some informtion like this :

[Root]
Mode=File
IPAddress=0
SocketPort=5000
EnableSocketServer=Y
SerialPort=2
BaudRate=9600
Parity=N
StopBits=1
DataBits=8
EnableLogFile=Y
EnableLogScreen=N
MaxNumResultsFile=9999
OutcomingResultsFileFormat=Mac
Name=default
PoolTime=5

and i would like to read this file, and take the ‘default’ Name and put it in a variable in my rust code.

So i began with this :

	let f = match File::open("file.ini") {
    	Err(err)=> {
       		println!("Couldn't open file.ini");
       		return;
    	},
    	Ok(f) => f,
	};

but i didn’t find how to acces a specific line and acces add the data to a variable too.

If anyone could help me :slight_smile:

Thanks !


#2

You could read your file line by line using a BufReader.

let reader = BufReader::new(f);

for line in reader.lines() {
    if line.starts_with("Name=") {
        // that's the line you want
    }
}

#3

Looks like a INI-style format, take your pick: https://crates.io/search?q=ini :slight_smile:


#4

Hello, and thanks you both of you for your answer :slight_smile:

I took the ini-syle format option and i have an other small problem, i’m trying to handle every error but i’m stuck on a point.

When i ‘open’ the file i succeed to manage the error :

	let lis_properties = match Ini::load_from_file("/path/file"){
		Ok(ini)=> ini,
		Err(err)=> {
			error!("Error : {:?}",err );
			return;
		},	
	};

but when i try to do the same thing on section and variable i’m stuck (don’t know what do put in the Ok section i guess)

	let root_section = lis_properties.section(Some("Root".to_owned())).unwrap();
	let lis_name_properties = root_section.get("LisName").unwrap();

those are the lines i can’t find how to handle the error.

Do you guys have a idea how to fix this ?

Thanks !


#5

Looks like section returns an Option<&Properties> and Properties is just a type alias for HashMap<String, String>, which means its get() returns an Option as well.

So, the above APIs don’t return an Error, but you do need to handle (or not, as in your code snippet above where you unwrap) the absence of the section you’re looking for and then of the property in that section. How would you like to handle them? Or do you want to return an error to the caller and let them deal with it?