deeznuts
deeznuts

Reputation: 1

how to pass every line from a text file as an argument in rust

i have made this code to check for alive urls in a text file it was first to check for a single url the script worked but then i wanted to make it multithreaded i got this error

error

here is the original code :

use hyper_tls::HttpsConnector;
use hyper::Client;
use tokio::io::BufReader;



#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {

    let https = HttpsConnector::new();
    let url = std::env::args().nth(1).expect("no list given");
    let client = Client::builder().build::<_, hyper::Body>(https);

    let reader = BufReader::new(url);
    let lines = reader.lines(); 
      

for l in lines {    

    let sep = l.parse()?;

   // Await the response...
    let resp = client.get(sep).await?;

if resp.status() == 200 {
   println!("{}", l);}

if resp.status() == 301 {
   println!("{}", l); }

   }


     Ok(())    
}

Upvotes: 0

Views: 1882

Answers (1)

LordMZTE
LordMZTE

Reputation: 227

the issue seems to be that you are passing in the file's name as opposed to its content to the BufReader.

In order to read the contents instead, you can use a tokio::fs:File. Here's an example of reading a file and printing its lines to stdout using tokio and a BufReader:

use tokio::{
    fs::File,
    io::{
        // This trait needs to be imported, as the lines function being
        // used on reader is defined there
        AsyncBufReadExt,
        BufReader
    }
};

#[tokio::main]
async fn main() {
    // get file command line argument
    let file_argument = std::env::args().nth(1).expect("Please provide a file as command line argument.");
    // open file
    let file = File::open(file_argument).await.expect("Failed to open file");
    // create reader using file
    let reader = BufReader::new(file);
    // get iterator over lines
    let mut lines = reader.lines();

    // this has to be used instead of a for loop, since lines isn't a
    // normal iterator, but a Lines struct, the next element of which
    // can be obtained using the next_line function.
    while let Some(line) = lines.next_line().await.expect("Failed to read file") {
        // print current line
        println!("{}", line);
    }
}


Upvotes: 5

Related Questions