I am super new to Rust, and I need some help.
I’m attempting to read a file that looks like this:
POWER_SUPPLY_NAME=BAT0
POWER_SUPPLY_STATUS=Full
POWER_SUPPLY_PRESENT=1
POWER_SUPPLY_TECHNOLOGY=Li-poly
POWER_SUPPLY_CYCLE_COUNT=0
POWER_SUPPLY_VOLTAGE_MIN_DESIGN=11400000
POWER_SUPPLY_VOLTAGE_NOW=12774000
POWER_SUPPLY_POWER_NOW=0
POWER_SUPPLY_ENERGY_FULL_DESIGN=90060000
POWER_SUPPLY_ENERGY_FULL=78710000
POWER_SUPPLY_ENERGY_NOW=78710000
POWER_SUPPLY_CAPACITY=100
POWER_SUPPLY_CAPACITY_LEVEL=Full
POWER_SUPPLY_MODEL_NAME=00NY492
POWER_SUPPLY_MANUFACTURER=LGC
POWER_SUPPLY_SERIAL_NUMBER= 699
This is the /sys/class/power_supply/BATx/uevent
file in linux that contains information about your battery, and I want to extract the 100
as an integer from the POWER_SUPPLY_CAPACITY
field, and the Full
as a string out of the POWER_SUPPLY_STATUS
field.
Here is the code I have so far.
use std::io::{self, Write};
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
fn main() {
let f = File::open("/home/matthew/Downloads/uevent").expect("Can't find file!");
let mut reader = BufReader::with_capacity(1000,f);
let mut contents = String::with_capacity(1000);
//Read the entire file as a string
reader.read_to_string(&mut contents).expect("Can't read file!");
//Print the contents
println!("{}", contents);
}
I’m aware of the .parse::<i32>
method to convert a string to an integer, and the .find()
method for searching for substrings within strings. However, I can’t figure out out to seek to the proper position in the string so that I can read the 100
(or whatever other number happens to be there) as an integer. What else do I need to do?
If this were C, I would simply use strstr()
to search for, and seek to the position in the string, and then just use strtol()
to read the 100
as an integer. Since I’m trying to learn Rust, I want to do it the Rust way.