How to resolve the algorithm Create a file step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Create a file step by step in the Rust programming language

Table of Contents

Problem Statement

In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Create a file step by step in the Rust programming language

Source code in the rust programming language

use std::io::{self, Write};
use std::fs::{DirBuilder, File};
use std::path::Path;
use std::{process,fmt};

const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";

fn main() {
    create(".").and(create("/"))
               .unwrap_or_else(|e| error_handler(e,1));
}


fn create<P>(root: P) -> io::Result<File>
    where P: AsRef<Path>
{
    let f_path = root.as_ref().join(FILE_NAME);
    let d_path = root.as_ref().join(DIR_NAME);
    DirBuilder::new().create(d_path).and(File::create(f_path))
}

fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "Error: {}", error);
    process::exit(code)
}


  

You may also check:How to resolve the algorithm Chinese remainder theorem step by step in the Crystal programming language
You may also check:How to resolve the algorithm Echo server step by step in the Forth programming language
You may also check:How to resolve the algorithm Pick random element step by step in the EasyLang programming language
You may also check:How to resolve the algorithm LZW compression step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Straddling checkerboard step by step in the Lua programming language