Skip to content

Trying to read directory with BufReader::lines while filtering errors consumes 100% CPU #43504

Closed
@mkpankov

Description

@mkpankov

If we File::open() a directory, then wrap it in BufReader, call lines() and then filter_map() only successful reads, the programs never finishes:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() {
    let file = File::open(".").unwrap();
    let reader = BufReader::new(file);
    let lines = reader.lines();
    // Comment to make it output infinite errors
    let lines = lines.filter_map(|s| s.ok());
    for line in lines {
        println!("Line: {:?}", line);
    }
    println!("Finished");
}

"Finished" is never printed. No "Line: ..." lines are printed. Instead 100% CPU is consumed.

Commenting the filter_map() line makes it output infinite Line: Err(Error { repr: Os { code: 21, message: "Is a directory" } }).

https://play.rust-lang.org/?gist=f6f0fdbcc83b9630b493c025e3432d31&version=stable

Looks similar to #34703, but not sure it's because of same reasons.

Not sure what would a proper fix would be, but I think I'd prefer lines() to output a single item with error instead of spamming it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions