Last active
August 29, 2015 14:20
-
-
Save sitano/1c5e6272084f1fde76b3 to your computer and use it in GitHub Desktop.
Sample file copy / temp / creation in RUST (1.0.0-beta2)
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
#[allow(unused_imports)] | |
use std::io; | |
use std::path::Path; | |
use std::fs::File; | |
type IoResult<T> = std::io::Result<T>; | |
extern crate tempdir; | |
extern crate rustc_serialize; | |
extern crate docopt; | |
use tempdir::*; | |
use docopt::Docopt; | |
static USAGE: &'static str = " | |
Usage: cp <source> <dest> | |
"; | |
#[derive(RustcDecodable, Debug)] | |
struct Args { | |
arg_source: String, | |
arg_dest: String | |
} | |
fn main() { | |
let args: Args = Docopt::new(USAGE) | |
.and_then(|d| d.decode()) | |
.unwrap_or_else(|e| e.exit()); | |
println!("{:?}", args); | |
println!("{:?}", process( | |
Path::new(&args.arg_source), | |
Path::new(&args.arg_dest))) | |
} | |
fn process(from: &Path, to: &Path) -> IoResult<u64> { | |
// creates a new tempdir with the specified suffix | |
let tempdir = try!(TempDir::new("skylight")); | |
// open the input file | |
let mut from_file = try!(File::open(from)); | |
// create a temporary file inside the tempdir | |
let mut tempfile = | |
try!(File::create(&tempdir.path().join("tmp1"))); | |
// copy the input file into the tempfile | |
try!(io::copy(&mut from_file, &mut tempfile)); | |
// after processing, copy the tempfile into the output file | |
let mut out = try!(File::create(to)); | |
return io::copy(&mut tempfile, &mut out); | |
} | |
/* toml: dependencies | |
[package] | |
name = "rust_file_copy_test" | |
version = "0.0.1" | |
authors = [ "john.koepi" ] | |
[dependencies] | |
tempdir = "*" | |
docopt = "*" | |
rustc-serialize = "*" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment