Last active
January 8, 2024 12:48
-
-
Save p1mo/eada19e065f7ebe87b1da1252877f516 to your computer and use it in GitHub Desktop.
Read Logfiles line by line in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io::Seek; | |
use std::io::BufRead; | |
use std::io::SeekFrom; | |
use std::io::BufReader; | |
#[cfg(windows)] | |
const OS_STRING_ENDING: &'static str = "\r\n"; | |
#[cfg(not(windows))] | |
const OS_STRING_ENDING: &'static str = "\n"; | |
pub fn current_size(path : &str) -> std::io::Result<u64> { | |
Ok(File::open(path)?.metadata()?.len()) | |
} | |
pub fn read_lines(path : &str, time : u64, offset : u64) -> std::io::Result<()> { | |
let mut position = offset; | |
loop { | |
let file = File::open(path)?; | |
let mut reader = BufReader::new(file); | |
position = reader.seek(SeekFrom::Start(position))?; | |
for resline in reader.lines() { | |
let line = resline?; | |
if line.len() == 0 { | |
continue; | |
} | |
// print line | |
println!("> {}", line); | |
position += (line.as_bytes().len() + OS_STRING_ENDING.len()) as u64; | |
} | |
std::thread::sleep(std::time::Duration::from_millis(time)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment