Created
July 11, 2016 20:42
-
-
Save mattnenterprise/0bdf38cd87cffea070735bf1cd9bdd25 to your computer and use it in GitHub Desktop.
Saves files from an FTP server with a .txt extension
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
extern crate ftp; | |
use std::fs::File; | |
use std::str; | |
use std::io::{Result, Write}; | |
use ftp::FtpStream; | |
fn main() { | |
get_txt_ftp("127.0.0.1", "<username>", "<password>").unwrap_or_else(|err| | |
panic!("{}", err) | |
); | |
} | |
fn get_txt_ftp(addr: &str, user: &str, pass: &str) -> Result<()> { | |
let mut ftp_stream = try!(FtpStream::connect((addr, 21))); | |
try!(ftp_stream.login(user, pass)); | |
println!("Current dir: {}", try!(ftp_stream.pwd())); | |
let file_list = try!(ftp_stream.nlst(None)); | |
let files: Vec<String> = file_list.into_iter() | |
.filter(|name| name.ends_with(".txt")) // This could be replaced by regex if needed | |
.collect(); | |
for file in files { | |
println!("Saving: {}", file); | |
try!(ftp_stream.retr(file.as_str(), |stream| { | |
let mut file = File::create(file.clone()).unwrap(); | |
let mut buf = [0; 2048]; | |
loop { | |
match stream.read(&mut buf) { | |
Ok(0) => break, | |
Ok(n) => file.write_all(&buf[0..n]).unwrap(), | |
Err(err) => return Err(err) | |
}; | |
} | |
Ok(()) | |
})); | |
} | |
ftp_stream.quit() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment