File input/output (I/O) is an essential part of most system-level programs. It can be used for debugging, saving program states, handling user-specific data, and even interfacing with physical devices (thanks to POSIX block and character devices).
Prior to C++17, working with file I/O was difficult, as filesystem management had to be handled using non-C++ APIs, which are often unsafe, platform-specific, or even incomplete.
In this chapter, we will provide a hands-on review of how to open, read, and write to files, and work with paths, directories, and the filesystem. We will conclude by providing three different examples that demonstrate how to log to a file, tail an existing file, and benchmark the C++ file input/output APIs.
This chapter will cover the following topics:
- Ways to open a file
- Reading and writing to a file
- File utilities