Reading and writing files
Everything up to here happens inside your program. This chapter is about the parts that leave it: a file on disk, a path that breaks on Windows, a directory to walk.
All of it can fail, and none of it is the compiler’s problem — so every article here is as much about the error as the happy path.
Articles
Section titled “Articles”- How to read a file into a Stringread_to_string and the encoding assumption
- How to read a file line by lineBufReader, and why you need it
- How to read a file into bytesread, and when a String would have failed
- How to write to a filecreate, truncate, and what happens on error
- How to append to a file without overwriting itthe OpenOptions you have to spell out
- How to write a file atomicallytemp file plus rename, so a crash cannot truncate it
- How to copy or move a filefs::copy, fs::rename, and crossing a filesystem
- How to delete a file or a whole directoryremove_file, remove_dir_all, and what is permanent
- How to check whether a file or directory existsPath::exists and the race it hides
- How to list the files in a directoryread_dir, and skipping the entries that error
- How to walk a directory treerecursion, symlinks, and the walkdir crate
- How to create a directory and its parentscreate_dir versus create_dir_all
- How to get the current working directoryand why it is not where your binary lives
- How to find the path of the current executableso config files are found no matter the cwd
- How to join paths without breaking on WindowsPathBuf and push, not string concatenation
- How to read file metadatasize, modified time, and the permissions you cannot set
- How to work with temporary filestempfile, and cleanup that survives a crash
- How to watch files for changesnotify, and the editor save that fires twice
- How to read and write a tar.gz archiveflate2 plus tar, streaming
- How to resize an imagethe image crate, and picking a filter