Rust Files and IO
This chapter introduces I/O operations in the Rust language.
Receiving command-line arguments
Command-line programs are the most basic form of computer programs; almost all operating systems support them and base the running of visual programs on command-line mechanisms.
A command-line program must be able to receive arguments from the command-line environment; these arguments are usually separated by spaces after the command on a command line.
In many languages (such as Java and C/C++), environment arguments are passed to the program as parameters of the main function (often a string array), but in Rust the main function takes no parameters, and the developer has to retrieve the environment arguments through the std::env module, which is very simple:
Example
fn
main
(
)
{
let
args
=
std
::
env
::
args
(
)
;
println
!
(
"{:?}"
,
args
)
;
}
Now run the program directly:
Args { inner: ["D:\\rust\\greeting\\target\\debug\\greeting.exe"] }
Perhaps the result you get is much longer than this; that is normal. In this result, the Args struct contains an inner array that holds only a single string, representing the location of the currently running program.
But this data structure is hard to understand; no problem, we can simply iterate over it:
Example
fn
main
(
)
{
let
args
=
std
::
env
::
args
(
)
;
for
arg
in
args
{
println
!
(
"{}"
,
arg
)
;
}
}
Running result:
D:\rust\greeting\target\debug\greeting.exe
Arguments are generally meant to be iterated over, aren't they.
Now we open the long-untouched launch.json, find "args": [], where we can set the runtime arguments. We change it to "args": ["first", "second"], then save and run the program again. The result:
D:\rust\greeting\target\debug\greeting.exe
first
second
As a real command-line program, we have never actually used it; as a language tutorial we will not describe how to run a Rust program from the command line here. But if you are a trained developer, you should be able to find the location of the executable; you can try entering the directory and using command-line commands to test that the program receives command-line environment arguments.
Entering a command in the terminal
Earlier chapters explained in detail how to use command-line output, because of the needs of language learning -- without output you cannot debug a program. But getting input information from the command line is still very important for a command-line program.
In Rust, the std::io module provides functionality related to standard input (which can be considered command-line input):
Example
use
std
::
io
::
stdin
;
fn
main
(
)
{
let
mut
str_buf
=
String
::
new
(
)
;
stdin
(
)
.read_line
(
&
mut
str_buf
)
.expect
(
"Failed to read line."
)
;
println
!
(
"Your input line is \n{}"
,
str_buf
)
;
}
Making the VSCode environment support command-line input is a very tedious matter, involving cross-platform issues and debugging problems, so we run the program directly in the VSCode terminal. Run it on the command line:
D:\rust\greeting> cd ./target/debug
D:\rust\greeting\target\debug> ./greeting.exe
RUNOOB
Your input line is
RUNOOB
std::io::Stdio contains the read_line reading method, which reads a line of string into a buffer. The return value is a Result enum, used to convey errors that occur during reading, so the expect or unwrap functions are commonly used to handle errors.
Note: Currently the Rust standard library does not provide a method to read numbers or formatted data directly from the command line; we can read a line of string and use string parsing functions to process the data.
File reading
We create a file text.txt in the D:\ directory of the computer, with the following contents:
This is a text file.
This is a program that reads the contents of a text file into a string:
Example
use
std
::
fs
;
fn
main
(
)
{
let
text
=
fs
::
read_to_string
(
"D:\text.txt"
)
.unwrap
(
)
;
println
!
(
"{}"
,
text
)
;
}
Running result:
This is a text file.
In Rust, reading an entire file that fits in memory is extremely easy; the read_to_string method in the std::fs module can easily accomplish the reading of a text file.
But if the file to be read is a binary file, we can use the std::fs::read function to read a collection of u8 values:
Example
use
std
::
fs
;
fn
main
(
)
{
let
content
=
fs
::
read
(
"D:\text.txt"
)
.unwrap
(
)
;
println
!
(
"{:?}"
,
content
)
;
}
Running result:
[84, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 120, 116, 32, 102, 105, 108, 101, 46]
The above two approaches are one-shot reads, very suitable for Web application development. But for some low-level programs, the traditional stream-based reading approach is still irreplaceable, because in most cases the file size may far exceed the memory capacity.
Stream-based file reading in Rust:
Example
use
std
::
io
::
prelude
::*;
use
std
::
fs
;
fn
main
(
)
{
let
mut
buffer
=
[
0u8
;
5
]
;
let
mut
file
=
fs
::
File
::
open
(
"D:\text.txt"
)
.unwrap
(
)
;
file.read
(
&
mut
buffer
)
.unwrap
(
)
;
println
!
(
"{:?}"
,
buffer
)
;
file.read
(
&
mut
buffer
)
.unwrap
(
)
;
println
!
(
"{:?}"
,
buffer
)
;
}
Running result:
[84, 104, 105, 115, 32]
[105, 115, 32, 97, 32]
The File class in the std::fs module is a class describing a file and can be used to open a file. After opening the file, we can use the File's read method to read the next few bytes of the file as a stream into a buffer (the buffer is a u8 array), and the number of bytes read equals the length of the buffer.
Note: VSCode currently does not have the ability to automatically add standard library references, so sometimes an error like "function or method does not exist" may be a problem with the standard library reference. We can view the documentation comments of the standard library (which appear when you hover the mouse over it) to manually add the standard library.
The open method of std::fs::File opens a file "read-only", and there is no accompanying close method, because the Rust compiler can automatically close the file when it is no longer in use.
File writing
File writing is divided into one-shot writing and stream writing. Stream writing requires opening a file, and there are two ways to open it: "create" and "append".
One-shot writing:
Example
use
std
::
fs
;
fn
main
(
)
{
fs
::
write
(
"D:\text.txt"
,
"FROM RUST PROGRAM"
)
.unwrap
(
)
;
}
This is as simple and convenient as one-shot reading. After running the program, the contents of the D:\text.txt file will be overwritten with FROM RUST PROGRAM. Therefore, use one-shot writing with caution! Because it directly deletes the file contents (no matter how large the file is). If the file does not exist, it will be created.
If you want to write file contents in a stream, you can use the create method of std::fs::File:
Example
use
std
::
io
::
prelude
::*;
use
std
::
fs
::
File
;
fn
main
(
)
{
let
mut
file
=
File
::
create
(
"D:\text.txt"
)
.unwrap
(
)
;
file.write
(
b
"FROM RUST PROGRAM"
)
.unwrap
(
)
;
}
This program is equivalent to the previous one.
Note: An opened file must be stored in a mutable variable in order to use the File methods!
There is no append static method in the File class, but we can use OpenOptions to open a file in a specific way:
Example
use
std
::
io
::
prelude
::*;
use
std
::
fs
::
OpenOptions
;
fn
main
(
)
->
std
::
io
::
Result
<
(
)
{
let
mut
file
=
OpenOptions::
new
(
)
.append
(
true
)
.open
(
"D:\text.txt"
)
?
;
file.write
(
b
" APPEND WORD"
)
?
;
Ok
(
(
)
)
}
After running, the contents of D:\text.txt will become:
FROM RUST PROGRAM APPEND WORD
OpenOptions is a flexible way to open a file; it can set access permissions. Besides the append permission, there are also read and write permissions. If we want to open a file with read and write permissions, we can write it like this:
Example
use
std
::
io
::
prelude
::*;
use
std
::
fs
::
OpenOptions
;
fn
main
(
)
->
std
::
io
::
Result
<
(
)
{
let
mut
file
=
OpenOptions::
new
(
)
.read
(
true
)
.write
(
true
)
.open
(
"D:\text.txt"
)
?
;
file.write
(
b
"COVER"
)
?
;
Ok
(
(
)
)
}
After running, the contents of D:\text.txt will become:
COVERRUST PROGRAM APPEND WORD