US
14 MIN READ TIME
RUST

Code read/write system file tools

So, you woke up today wanting to know how to use file input and output calls to code system tools in Rust? Then Mihalis Tsoukalos can help.

QUIK TIP

» EXPECT AND UNWRAP

QUIK TIP

» THE VECTOR DATA TYPE

A Rust trait is a collection of methods defined for an unknown type: Self. Put simply, a trait describes an abstract interface that can be implemented by other data types. So traits define a behaviour. See https://doc. rust-lang.org/ std/io/trait. Read.html.

Both expect() and unwrap() are used with the Result and Option data types and allow you to deal with error and unexpected conditions. Put simply, they allow you to get the value from a Result or Option variable, if it exists, or deal with the error condition the way you want to. The generic format of a Result value is <&a_value, Error> , which means that we can either get Ok(&a_value) if it exists or get an Err(Error) value whereas the generic format of an Option value is Option<&a_value> , which means that we either get a valid value Some(&a_value) or None . Bear in mind that Some is a data constructor. You can learn more about Option and Some by visiting https://doc.rust-lang.org/std/option/enum.Option.html.

If you’re keen to experiment with file I/O in Rust, you can try implementing the cat utility. You could also write a utility that reads plain text files and replaces a predefined string with another one, and then writes the output to a different file.

The Vector data type is very popular in Rust, so it deserves some extra attention. First of all, a Vector is like an array. As is the case with arrays, index values start from 0. The main advantage of vectors over arrays is that vectors can be resized, provided that they’re declared as mutable. You can put or remove vector elements using pop() and push(), respectively. Additionally, apart from the size, which is the number of elements stored, a vector has a capacity, which is the amount of memory reserved for the vector. Finally, a vector represents a pointer to the data.

OUR EXPERT

Having a Result value returned by a function named get_result() , we can extract its data as follows:

You can select the part of a Vector that you want to access using an index range, as occurs in read.rs. So, for a vector named a_vector, you can select its first two elements by writing &a_vector[0..2] . You can iterate over the elements of a vector in various ways. One such way is by using a for loop using the index of the element you want to access. Another approach is to use an iterator, which for a_vector is called as a_vector.iter() , to obtain all vector elements one by one. Remember that if you use an index value greater than or equal to the length of the vector, your code is going to crash.

Mihalis Tsoukalos is a systems engineer and a technical writer. You can reach him at @mactsouk.

Unlock this article and much more with
You can enjoy:
Enjoy this edition in full
Instant access to 600+ titles
Thousands of back issues
No contract or commitment
Try for 99c
SUBSCRIBE NOW
30 day trial, then just $9.99 / month. Cancel anytime. New subscribers only.


Learn more
Pocketmags Plus
Pocketmags Plus

This article is from...


View Issues
Linux Format
July 2022
VIEW IN STORE

Other Articles in this Issue


WELCOME
Open source security
Jonni’s playing with his little bag of open
REGULARS AT A GLANCE
Nvidia moves to open source kernel drivers
DRIVERS
LVFS hits 50 million updates
The Linux Vendor Firmware Service has now delivered a huge 50 million updates for computers around the world.
BLUETOOTH IN PIPEWIRE
Frederic Danis is a senior software engineer at
Razer releases stylish Linux laptop
Collaboration between the high-end laptop company and Lambda is powerful… and expensive.
GOING FOR GOLD!
Keith Edmunds is MD of Tiger Computing Ltd,
GNOME patent troll is finally stomped on
Rothschild Patent Imaging (RPI) forced to give up its patent rights.
GitLab moves to AlmaLinux
Development comes after CentOS 8 enters End of Life.
Firefox hits 100
Mozilla celebrates version 100.0 of its famed browser.
Distro watch
What’s down the side of the free software sofa?
PLAN FOR THE FUTURE
Matt Yonkovit is the head of open source
OPEN NVIDIA
Jon Masters has been involved with Linux for
KERNEL WATCH
Jon Masters summarises the latest happenings in the Linux kernel, because someone has to…
Answers
Got a burning question about open source or the kernel? Whatever your level, email it to lxf.answers@futurenet.com
Mailserver
WRITE TO US Do you have a burning
CherryTree
THE BEST NEW OPEN SOURCE SOF T WARE
Sherlock
Version: N/A Web: https://sherlock-project.github.io In addition
Simple Keylogger
Version: 2.7.1 Web: https://simplekeylogger.github.io The keylogger
Siren
Version: 0.10 Web: www.kariliq.nl/siren All operations
MediaInfo
Version: 22.03 Web: https://mediaarea . net/en/MediaInfo The project’s
Mechvibes
Version : 2.3.1 Web: https://mechvibes.com Mechvibes
yt-dlp
Version: 2022.04.08 Web: https://github.com/yt-dlp/yt-dlp Despite its
Eternal Lands
Version: 1.9.6 Web: www.eternal-lands.com If you
Speed Dreams
Version: 2.2.3 Web: www.speed-dreams.org Speed Dream developers
Snap Backup
Version: 6.4.0 Web: https://snapbackup.org Snap Backup
ugrep
Version: 3.7.9 Web: https://github.com/genivia/ugrep Ugrep includes built-in
REVIEWS
AMD Ryzen 7 5800X3D
Dave James contemplates what it is to be the fastest.
TurnKey Linux 17.0
Lethargy and laziness often get the best of him, but sometimes Mayank Sharma can turn the tables to his advantage.
Rolling Rhino Remix
A rolling Ubuntu release sounds so outrageous Mayank Sharma had to see for himself if it really delivers on its word and isn’t just a gimmick.
SysLinuxOS 11.3
Distros that take the kitchen sink approach don’t really appeal to Mayank Sharma… until, of course, he finds one that does.
Q4OS 4.8
Neither a big KDE user nor a fan of Windows, and yet Mayank Sharma can’t resist the charm of this KDE distro and its Windows installer.
Shattered Pixel Dungeon
The only certainties in life are death, taxes and middle management, and Neil Mohr knows which two are the least painful to deal with.
ROUNDUP
Full-featured CMS
Michael Reed takes a good look at five heavyweight professional content management systems that are all open source and completely free.
Get installed
Is the installation routine a helping hand or more of a slap in the face?
Support and community
Help for using the CMS and what to do when we hit difficulties.
The content editor
This is where you’ll be working in the CMS
Themes and customisation
How easy is it to change the look and layout of your site?
Suitability for beginners
You might be an expert, but the user of the system might not be.
Extra features
Does one CMS have any niceties that the other systems lack?
Extensions
Beyond the defaults, to what degree can you add features easily?
The verdict
Content management systems
HACKER’S TOOLKIT 2O22
Pretty boy and known pirate Jonni Bidwell shows how to tame your Parrot. Parrot Security OS, that is… 2022
Hack the planet/Parrot
Get started with a persistent USB install of Parrot Security OS
Hacking 101
Starting with the humble ping command and moving on to some stealthy network recon activities…
Nmap deep dive
Nmap, the stealthy port scanner, is a vital tool for any helpful hacker or nefarious network administrator’s arsenal.
Modern hacking, ethics and statistics
Read about the largest DDoS in history and how honing your hacking skills might help you prevent the next one…
Pi USER
CAUSING A PICO SCENE
Les Pounder works with groups such as the Raspberry Pi Foundation to help boost people’s maker skills
Rock Pi expands its range
Less appetising but just as filling, the China-based Rock Pi now delivers some SBC competition.
GPUs ARE GOish
External Pi ones.
299 winners!
Blasted into space.
Amiberry v5.0
Les Pounder loves the Amiga – he even started his journalism career with custom “disk magazines” on the school playground.
Pimoroni Servo 2040
Achieve precise motion control from Les Pounder’s tiny package.
Cheaper sense and sensor-abilities
The ever-frugal Les Pounder reveals how two of the cheapest sensors on the market can bring a wealth of data to your Raspberry Pi project.
Build your own smart home sensors
Discover how to install micro controllers and simple electronics to make our homes almost as smart as Matt Holder.
Set your Pi for mobile streaming video
Sean Conway helps you ride the rails with a Raspberry Pi and its camera, with a bit of streaming video trickery thrown in for good measure.
IN DEPTH
LINUX IN SPACE!
From a shaky start, Linux is becoming much more established in astronautics. Mike Bedford looks at its success to date and its future prospects.
TUTORIALS
Making presentations from the command line
Although renowned for concocting far better excuses than cocktails, Shashank Sharma is quite adept at making presentations.
How to control Docker over the internet
Nick Peers discovers a user-friendly, convenient and powerful way to administer your Docker containers from wherever you happen to be.
Emulate the classic 8-bit Commodore 16
Les Pounder revisits Commodore’s low-cost computer from the mid-80s and finds out how it compares to its more illustrious stablemate.
How to roll your own Linux packages
Installing from existing repos is too easy for Aaron Peters, who’s decided to build his own native package. Here’s how you can follow in his footsteps.
Design 3D parts with computer aided design
Make a 3D part in FreeCAD’s Sketcher workbench with Michael Reed, even if you think an orthographic view is the inside of someone’s mouth.
Set up picture-perfect online photo storage
In a flurry of paranoia, David Rutland expels Google Photos from his life and sets up self-hosted photo storage on the semi-official Linux Format VPS.
TOP OF THE FOSS!
TOP OF THE POP! _OS
System76 developer Michael Murphy shares his Pop!_OS insights with Linux Format’s self-proclaimed top Pop fan Jonni Bidwell.
CODING ACADEMY
Use Home Assistant NodeRED devices
NodeRED is a graphical programming language that’s ideally suited to IoT, electronics and home automations, reveals Matt Holder.
Chat
X
Pocketmags Support