I/O
I/O
Rust I/O is kind of awkward, as befits a C-like language. But it's pretty fast
Rust I/O is cross-platform for the Big Three; works fine with all of them
Basic support is in
std::io
,std::fs
,std::path
,std::process
,std::net
and a few other placesProbably easiest by starting with a good example similar to what you want to do and trying to understand how it works
Basics
Basic I/O is on things with the
Read
,BufRead
andWrite
traitsAny sensible thing, including strings, either is
Read
/Write
or can be made to be: seestd::io::Cursor
for bytes to/from an arbitrary sourceRead
= "unbuffered";BufRead
implementsBufReader
; there is noBufWrite
The
BufReader
andBufWriter
structs can be used to add a buffering wrapper. These are block buffers with a user-specified blocksize
Stdio
stdin
,stdout
andstderr
are treated as functions returning readers / writers, because locking across threadsThe borrow rules will confuse you at first
The
flush()
situation is non-optimal. Standard input is line buffered, standard output is line buffered. This cannot be easily changed. Prompting is quite trickyhttp://github.com/BartMassey/prompted
Paths
std::path
is the right way to deal with filenames and pathnamesPathBuf
is the owned type forPath
. String types etc areAsRef<Path>
PathBuf
has the notion ofpush()
andpop()
for pathname components — see the docsPathBuf
is an abstraction overOsString
, allowing the local path characters and separators to be used correctly
Files
Basic open/close etc are fairly obvious
Directory operations are supported
Usually wrap a file in a
BufReader
orBufWriter
The interface is a bit weird because zero-copy attempts and scatter/gather and stuff
std::cursor::Cursor
is a neat way to get "fake files" for tests, etc
Networking
Reasonable TCP/IP interface in
std::net
The
SocketAddr
struct deals with ports, which is nicehttp://github.com/pdx-cs-rust/net-15