Added code snippets

master
peshwar9 3 years ago
parent 46a80acddf
commit 28bdc5bf65

@ -0,0 +1,9 @@
use std::fs;
fn main() {
let entries = fs::read_dir("/tmp").unwrap();
for entry in entries {
if let Ok(entry) = entry {
println!("{:?}", entry.path());
}
}
}

@ -0,0 +1,4 @@
use std::time::SystemTime;
fn main() {
let _now = SystemTime::now();
}

@ -0,0 +1,7 @@
use std::thread::sleep;
use std::time::{Duration, Instant};
fn main() {
let now = Instant::now();
sleep(Duration::new(3, 0));
println!("{:?}", now.elapsed().as_secs());
}

@ -0,0 +1,8 @@
use dotenv::dotenv;
use std::env;
fn main() {
dotenv().ok();
for (key, value) in env::vars() {
println!("{}:{}", key, value);
}
}

@ -0,0 +1,6 @@
use std::env;
fn main() {
for argument in env::args() {
println!("{}", argument);
}
}

@ -0,0 +1,11 @@
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let size = &args[1];
let mode = &args[2];
let source_folder = &args[3];
println!(
"Size:{},mode:{},source folder: {}",
size, mode, source_folder
);
}

@ -0,0 +1,4 @@
use std::fs::File;
fn main() {
let file = File::create("./stats.txt");
}

@ -0,0 +1,8 @@
use std::fs::DirBuilder;
fn main() {
let dir_structure = "/tmp/dir1/dir2/dir3";
DirBuilder::new()
.recursive(true)
.create(dir_structure)
.unwrap();
}

@ -0,0 +1,10 @@
use std::path::PathBuf;
fn main() {
let mut f_path = PathBuf::new();
f_path.push(r"/tmp");
f_path.push("packt");
f_path.push("rust");
f_path.push("book");
f_path.set_extension("rs");
println!("Path constructed is {:?}", f_path);
}

@ -0,0 +1,6 @@
use std::fs;
fn main() -> std::io::Result<()> {
fs::hard_link("stats.txt", "./statsa.txt")?; // Hard
// link stats.txt to statsa.txt
Ok(())
}

@ -0,0 +1,7 @@
use std::fs;
use std::os::unix::fs as fsunix;
fn main() {
fsunix::symlink("stats.txt", "sym_stats.txt").expect("Cannot create symbolic link");
let sym_path = fs::read_link("sym_stats.txt").expect("Cannot read link");
println!("Link is {:?}", sym_path);
}

@ -0,0 +1,11 @@
use std::fs::File;
use std::fs::OpenOptions;
fn main() {
// Method 1
let _file1 = File::open("stats1.txt").expect("File not found");
// Method 2
let _file2 = OpenOptions::new()
.write(true)
.create(true)
.open("stats2.txt");
}

@ -0,0 +1,4 @@
use std::fs;
fn main() {
fs::copy("stats1.txt", "stats2.txt").expect("Unable to copy");
}

@ -0,0 +1,4 @@
use std::fs;
fn main() {
fs::rename("stats1.txt", "stats3.txt").expect("Unable to rename");
}

@ -0,0 +1,10 @@
use std::fs;
fn main() {
let byte_arr = fs::read("stats3.txt").expect("Unable to read file into bytes");
println!(
"Value read from file into bytes is {}",
String::from_utf8(byte_arr).unwrap()
);
let string1 = fs::read_to_string("stats3.txt").expect("Unable to read file into string");
println!("Value read from file into string is {}", string1);
}

@ -0,0 +1,4 @@
use std::fs;
fn main() {
fs::write("stats3.txt", "Rust is exciting,isn't it?").expect("Unable to write to file");
}

@ -0,0 +1,19 @@
use std::fs;
fn main() {
let file_metadata = fs::metadata("stats.txt").expect("Unable to get file metadata");
println!(
"Len: {}, last accessed: {:?}, modified : {:?}, created: {:?}",
file_metadata.len(),
file_metadata.accessed(),
file_metadata.modified(),
file_metadata.created()
);
println!(
"Is file: {}, Is dir: {}, is Symlink: {}",
file_metadata.is_file(),
file_metadata.is_dir(),
file_metadata.file_type().is_symlink()
);
println!("File metadata: {:?}", fs::metadata("stats.txt"));
println!("Permissions of file are: {:?}", file_metadata.permissions());
}

@ -0,0 +1,7 @@
use std::fs;
fn main() {
let mut permissions = fs::metadata("stats.txt").unwrap().permissions();
permissions.set_readonly(true);
let _ = fs::set_permissions("stats.txt", permissions).expect("Unable to set permission");
fs::write("stats.txt", "Hello- Can you see me?").expect("Unable to write to file");
}

@ -0,0 +1,24 @@
use std::fs;
use std::path::Path;
fn main() {
let dir_entries = fs::read_dir(".").expect("Unable to read directory contents");
// Read directory contents
for entry in dir_entries {
//Get details of each directory entry
let entry = entry.unwrap();
let entry_path = entry.path();
let entry_metadata = entry.metadata().unwrap();
let entry_file_type = entry.file_type().unwrap();
let entry_file_name = entry.file_name();
println!(
"Path is {:?}.\n Metadata is {:?}\n File_type is {:?}.\n Entry name is{:?}.\n",
entry_path, entry_metadata, entry_file_type, entry_file_name
);
}
// Get path components
let new_path = Path::new("/usr/d1/d2/d3/bar.txt");
println!("Path parent is: {:?}", new_path.parent());
for component in new_path.components() {
println!("Path component is: {:?}", component);
}
}

@ -0,0 +1,6 @@
use std::process::Command;
fn main() {
Command::new("ls")
.spawn()
.expect("ls command failed to start");
}

@ -0,0 +1,21 @@
use std::io::prelude::*;
use std::process::{Command, Stdio};
fn main() {
let process = match Command::new("rev")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
{
Err(err) => panic!("couldn't spawn rev: {}", err),
Ok(process) => process,
};
match process.stdin.unwrap().write_all("palindrome".as_bytes()) {
Err(why) => panic!("couldn't write to stdin: {}", why),
Ok(_) => println!("sent text to rev command"),
}
let mut child_output = String::new();
match process.stdout.unwrap().read_to_string(&mut child_output) {
Err(err) => panic!("couldn't read stdout: {}", err),
Ok(_) => print!("Output from child process is:\n{}", child_output),
}
}

@ -0,0 +1,7 @@
use std::process::Command;
fn main() {
Command::new("env")
.env("MY_PATH", "/tmp")
.spawn()
.expect("Command failed to execute");
}

@ -0,0 +1,7 @@
use std::process::Command;
fn main() {
Command::new("env")
.env_clear()
.spawn()
.expect("Command failed to execute");
}

@ -0,0 +1,14 @@
use std::process::{Command, Stdio};
fn main() {
let _child_process = match Command::new("invalid-command")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
{
Err(err) => panic!("Unable to spawn child process: {}", err),
Ok(new_process_handle) => {
println!("Successfully spawned child process");
new_process_handle
}
};
}

@ -0,0 +1,19 @@
use std::panic;
use std::process::{Command, Stdio};
fn main() {
panic::set_hook(Box::new(|_| {
println!(
" This is an example of custom panic
hook, which is invoked on thread panic, but
before the panic run-time is invoked"
)
}));
let _child_process = match Command::new("invalid-command")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
{
Err(err) => panic!("Normal panic message {}", err),
Ok(new_process_handle) => new_process_handle,
};
}

@ -0,0 +1,22 @@
use signal_hook::iterator::Signals;
use std::io::Error;
fn main() -> Result<(), Error> {
let signals = Signals::new(&[signal_hook::SIGTERM, signal_hook::SIGINT])?;
'signal_loop: loop {
// Pick up signals that arrived since last time
for signal in signals.pending() {
match signal {
signal_hook::SIGINT => {
println!("Received signal SIGINT");
}
signal_hook::SIGTERM => {
println!("Received signal SIGTERM");
break 'signal_loop;
}
_ => unreachable!(),
}
}
}
println!("Terminating program");
Ok(())
}

@ -0,0 +1,8 @@
use std::process::Command;
fn main() {
Command::new("ls")
.arg("-l")
.arg("-h")
.spawn()
.expect("ls command failed to start");
}

@ -0,0 +1,4 @@
use std::process::Command;
fn main() {
Command::new("ls").args(&["-l", "-h"]).spawn().unwrap();
}

@ -0,0 +1,8 @@
use std::process::Command;
fn main() {
Command::new("ls")
.current_dir("..")
.args(&["-l", "-h"])
.spawn()
.expect("ls command failed to start");
}

@ -0,0 +1,8 @@
use std::process::Command;
fn main() {
let output = Command::new("cat").arg("a.txt").output().unwrap();
if !output.status.success() {
println!("Command executed with failing error code");
}
println!("printing: {}", String::from_utf8(output.stdout).unwrap());
}

@ -0,0 +1,7 @@
use std::process;
fn main() {
println!("Going to abort process");
process::abort();
// This statement will not get executed
println!("Process aborted");
}

@ -0,0 +1,7 @@
use std::process;
fn main() {
println!("Going to exit process with error code 64");
process::exit(64);
// execution never gets here
println!("Process exited");
}

@ -0,0 +1,12 @@
use std::process::Command;
fn main() {
let status = Command::new("cat")
.arg("non-existent-file.txt")
.status()
.expect("failed to execute cat");
if status.success() {
println!("Successful operation");
} else {
println!("Unsuccessful operation");
}
}

@ -0,0 +1,14 @@
use std::io::prelude::*;
use std::process::{Command, Stdio};
fn main() {
// Spawn the `ps` command
let process = match Command::new("ps").stdout(Stdio::piped()).spawn() {
Err(err) => panic!("couldn't spawn ps: {}", err),
Ok(process) => process,
};
let mut ps_output = String::new();
match process.stdout.unwrap().read_to_string(&mut ps_output) {
Err(err) => panic!("couldn't read ps stdout: {}", err),
Ok(_) => print!("ps output from child process is:\n{}", ps_output),
}
}

@ -0,0 +1,8 @@
use std::thread;
fn main() {
for _ in 1..5 {
thread::spawn(|| {
println!("Hi from thread id {:?}", thread::current().id());
});
}
}

@ -0,0 +1,13 @@
use std::thread;
fn main() {
let mut child_threads = Vec::new();
for _ in 1..5 {
let handle = thread::spawn(|| {
println!("Hi from thread id {:?}", thread::current().id());
});
child_threads.push(handle);
}
for i in child_threads {
i.join().unwrap();
}
}

@ -0,0 +1,16 @@
use std::thread;
fn main() {
let mut child_threads = Vec::new();
for i in 1..5 {
let builder = thread::Builder::new().name(format!("mythread{}", i));
let handle = builder
.spawn(|| {
println!("Hi from thread id {:?}", thread::current().name().unwrap());
})
.unwrap();
child_threads.push(handle);
}
for i in child_threads {
i.join().unwrap();
}
}

@ -0,0 +1,14 @@
use std::fs;
use std::thread;
fn copy_file() -> thread::Result<()> {
thread::spawn(|| {
fs::copy("a.txt", "b.txt").expect("Error occurred");
})
.join()
}
fn main() {
match copy_file() {
Ok(_) => println!("Ok. copied"),
Err(_) => println!("Error in copying file"),
}
}

@ -0,0 +1,31 @@
use std::fs;
use std::thread;
struct Filenames {
source: String,
destination: String,
}
impl Drop for Filenames {
fn drop(&mut self) {
if thread::panicking() {
println!("dropped due to panic");
} else {
println!("dropped without panic");
}
}
}
fn copy_file(file_struct: Filenames) -> thread::Result<()> {
thread::spawn(move || {
fs::copy(&file_struct.source, &file_struct.destination).expect("Error occurred");
})
.join()
}
fn main() {
let foo = Filenames {
source: "a1.txt".into(),
destination: "b.txt".into(),
};
match copy_file(foo) {
Ok(_) => println!("Ok. copied"),
Err(_) => println!("Error in copying file"),
}
}

@ -0,0 +1,8 @@
use std::thread;
use std::time::Duration;
fn main() {
let duration = Duration::new(1, 0);
println!("Going to sleep");
thread::sleep(duration);
println!("Woke up");
}

@ -1 +0,0 @@
{"rustc_fingerprint":4503571881771466578,"outputs":{"4476964694761187371":["___\nlib___.rlib\nlib___.dylib\nlib___.dylib\nlib___.a\nlib___.dylib\n/Users/prabhueshwarla/.rustup/toolchains/stable-x86_64-apple-darwin\ndebug_assertions\nproc_macro\ntarget_arch=\"x86_64\"\ntarget_endian=\"little\"\ntarget_env=\"\"\ntarget_family=\"unix\"\ntarget_feature=\"fxsr\"\ntarget_feature=\"sse\"\ntarget_feature=\"sse2\"\ntarget_feature=\"sse3\"\ntarget_feature=\"ssse3\"\ntarget_os=\"macos\"\ntarget_pointer_width=\"64\"\ntarget_vendor=\"apple\"\nunix\n",""],"1164083562126845933":["rustc 1.43.0 (4fb7144ed 2020-04-20)\nbinary: rustc\ncommit-hash: 4fb7144ed159f94491249e86d5bbd033b5d60550\ncommit-date: 2020-04-20\nhost: x86_64-apple-darwin\nrelease: 1.43.0\nLLVM version: 9.0\n",""]},"successes":{}}

@ -1 +0,0 @@
{"rustc":12217307662193597186,"features":"[]","target":8924639720479505415,"profile":14891217944882224483,"path":7862958152481923276,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/chapter9-16376659f5eb3df7/dep-bin-shared_state-16376659f5eb3df7"}}],"rustflags":[],"metadata":13779719443416291531}

@ -1 +0,0 @@
{"rustc":12217307662193597186,"features":"[]","target":8924639720479505415,"profile":1647870076477133176,"path":7862958152481923276,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/chapter9-27c22e2f1c68d890/dep-test-bin-shared_state-27c22e2f1c68d890"}}],"rustflags":[],"metadata":13779719443416291531}

@ -1 +0,0 @@
{"rustc":12217307662193597186,"features":"[]","target":6889418469635003774,"profile":1647870076477133176,"path":6514298648823649283,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/chapter9-b445dc07a468b340/dep-test-bin-message_passing-b445dc07a468b340"}}],"rustflags":[],"metadata":13779719443416291531}

@ -1 +0,0 @@
{"rustc":12217307662193597186,"features":"[]","target":6889418469635003774,"profile":14891217944882224483,"path":6514298648823649283,"deps":[],"local":[{"CheckDepInfo":{"dep_info":"debug/.fingerprint/chapter9-d411507d2e0fba19/dep-bin-message_passing-d411507d2e0fba19"}}],"rustflags":[],"metadata":13779719443416291531}

@ -1,5 +0,0 @@
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/message_passing-b445dc07a468b340.rmeta: src/message-passing.rs
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/message_passing-b445dc07a468b340.d: src/message-passing.rs
src/message-passing.rs:

@ -1,5 +0,0 @@
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/message_passing-d411507d2e0fba19.rmeta: src/message-passing.rs
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/message_passing-d411507d2e0fba19.d: src/message-passing.rs
src/message-passing.rs:

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -1,5 +0,0 @@
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/shared_state-16376659f5eb3df7.rmeta: src/shared-state.rs
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/shared_state-16376659f5eb3df7.d: src/shared-state.rs
src/shared-state.rs:

@ -1,5 +0,0 @@
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/shared_state-27c22e2f1c68d890.rmeta: src/shared-state.rs
/Users/prabhueshwarla/rust/author/packt/prod/chapter9/target/rls/debug/deps/shared_state-27c22e2f1c68d890.d: src/shared-state.rs
src/shared-state.rs:

@ -0,0 +1,10 @@
use std::fs::File;
use std::io::Read;
fn main() {
// Open a file
let mut f = File::open("records.txt").unwrap();
//Create a memory buffer to read from file
let mut buffer = [0; 1024];
// read from file into buffer
let _ = f.read(&mut buffer[..]).unwrap();
}

@ -0,0 +1,15 @@
use std::fs::File;
use std::io::Read;
fn main() {
// Open two file handles for reading
let f1 = File::open("file1.txt").unwrap();
let f2 = File::open("file2.txt").unwrap();
//Chain the two file handles
let mut chained_handle = f1.chain(f2);
// Create a buffer to read into
let mut buffer = String::new();
// Read from chained handle into buffer
chained_handle.read_to_string(&mut buffer).unwrap();
// Print out the value read into the buffer
println!("Read from chained handle:\n{}", buffer);
}

@ -0,0 +1,15 @@
use std::fs::File;
use std::io::Read;
fn main() -> std::io::Result<()> {
// Open two file handles for reading
let f1 = File::open("file1.txt")?;
let f2 = File::open("file3.txt")?;
//Chain the two file handles
let mut chained_handle = f1.chain(f2);
// Create a buffer to read into
let mut buffer = String::new();
// Read from chained handle into buffer
chained_handle.read_to_string(&mut buffer)?;
println!("Read from chained handle: {}", buffer);
Ok(())
}

@ -0,0 +1,30 @@
use std::fs::File;
use std::io::Read;
fn read_files(handle: &mut impl Read) -> std::io::Result<String> {
// Create a buffer to read into
let mut buffer = String::new();
// Read from chained handle into buffer
handle.read_to_string(&mut buffer)?;
Ok(buffer)
}
fn main() {
let mut chained_handle;
// Open two file handles for reading
let file1 = "file1.txt";
let file2 = "file3.txt";
if let Ok(f1) = File::open(file1) {
if let Ok(f2) = File::open(file2) {
//Chain the two file handles
chained_handle = f1.chain(f2);
let content = read_files(&mut chained_handle);
match content {
Ok(text) => println!("Read from chained handle:\n{}", text),
Err(e) => println!("Error occurred in reading files: {}", e),
}
} else {
println!("Unable to read {}", file2);
}
} else {
println!("Unable to read {}", file1);
}
}

@ -0,0 +1,13 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
// Open a file
let f = File::open("records.txt").unwrap();
// Create a BufReader, passing in the file handle
let mut buf_reader = BufReader::new(f);
//Create a memory buffer to read from file
let mut buffer = String::new();
// read a line into the buffer
buf_reader.read_line(&mut buffer).unwrap();
println!("Read the following: {}", buffer);
}

@ -0,0 +1,13 @@
use std::fs::File;
use std::io::{BufWriter, Write};
fn main() {
// Create a file
let f = File::create("file.txt").unwrap();
// Create a BufWriter, passing in the file handle
let mut buf_writer = BufWriter::new(f);
//Create a memory buffer
let buffer = String::from("Hello, testing");
// write into the buffer
buf_writer.write(buffer.as_bytes()).unwrap();
println!("wrote the following: {}", buffer);
}

@ -0,0 +1,9 @@
use std::io::{self, Write};
fn main() {
//Create a memory buffer to read from file
let mut buffer = String::new();
// read a line into the buffer
let _ = io::stdin().read_line(&mut buffer).unwrap();
// Write the buffer to standard output
io::stdout().write(&mut buffer.as_bytes()).unwrap();
}

@ -0,0 +1,17 @@
use std::io::{Read, Write};
fn main() {
//Create a memory buffer
let mut buffer = [8; 1024];
// Get handle to input stream
let stdin_handle = std::io::stdin();
// Lock the handle to input stream
let mut locked_stdin_handle = stdin_handle.lock();
// read a line into the buffer
locked_stdin_handle.read(&mut buffer).unwrap();
// Get handle to output stream
let stdout_handle = std::io::stdout();
// Lock the handle to output stream
let mut locked_stdout_handle = stdout_handle.lock();
// Write the buffer to standard output
locked_stdout_handle.write(&mut buffer).unwrap();
}

@ -0,0 +1,11 @@
use std::io::Write;
fn main() {
//Create a memory buffer
let buffer = b"Hello, this is error message from standard error stream\n";
// Get handle to output error stream
let stderr_handle = std::io::stderr();
// Lock the handle to output error stream
let mut locked_stderr_handle = stderr_handle.lock();
// write into error stream from buffer
locked_stderr_handle.write(buffer).unwrap();
}

@ -0,0 +1,11 @@
use std::io::{BufRead, BufReader};
fn main() {
// Create handle to standard input
let s = std::io::stdin();
//Create a BufReader instance to optimize sys calls
let file_reader = BufReader::new(s);
// Read from standard input line-by-line
for single_line in file_reader.lines() {
println!("You typed:{}", single_line.unwrap());
}
}

@ -0,0 +1,12 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
// Open a file for reading
let f = File::open("file.txt").unwrap();
//Create a BufReader instance to optimize sys calls
let file_reader = BufReader::new(f);
// Read from standard input line-by-line
for single_line in file_reader.lines() {
println!("Line read from file :{}", single_line.unwrap());
}
}

@ -0,0 +1,12 @@
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
// Open a file for reading
let f = File::open("file.txt").unwrap();
//Create a BufReader instance to optimize sys calls
let file_reader = BufReader::new(f);
// Read from standard input line-by-line
for single_line in file_reader.lines() {
println!("Line read from file :{}", single_line.unwrap());
}
}

Binary file not shown.

@ -1 +0,0 @@
{"rustc_fingerprint":4503571881771466578,"outputs":{"4476964694761187371":["___\nlib___.rlib\nlib___.dylib\nlib___.dylib\nlib___.a\nlib___.dylib\n/Users/prabhueshwarla/.rustup/toolchains/stable-x86_64-apple-darwin\ndebug_assertions\nproc_macro\ntarget_arch=\"x86_64\"\ntarget_endian=\"little\"\ntarget_env=\"\"\ntarget_family=\"unix\"\ntarget_feature=\"fxsr\"\ntarget_feature=\"sse\"\ntarget_feature=\"sse2\"\ntarget_feature=\"sse3\"\ntarget_feature=\"ssse3\"\ntarget_os=\"macos\"\ntarget_pointer_width=\"64\"\ntarget_vendor=\"apple\"\nunix\n",""],"1164083562126845933":["rustc 1.43.0 (4fb7144ed 2020-04-20)\nbinary: rustc\ncommit-hash: 4fb7144ed159f94491249e86d5bbd033b5d60550\ncommit-date: 2020-04-20\nhost: x86_64-apple-darwin\nrelease: 1.43.0\nLLVM version: 9.0\n",""]},"successes":{}}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save