Introduction
Working with the file system is one of the key tasks in any application programming. In C++, there are two main approaches: the classic one (using the <fstream> library) and the modern one (using the <filesystem> library, available starting from the C++17 standard). In this article, we will use practical examples to examine how to read and write files, create and delete directories, and check for file existence.
The material will be useful both for beginners just learning C++ and for experienced developers who want to refresh their knowledge of the language's modern capabilities.
1. Reading and Writing Text Files Using fstream
The <fstream> library provides classes for working with files: ifstream (reading), ofstream (writing), and fstream (reading and writing).
1.1. Writing Data to a File
To write to a file, we use an ofstream object. If the file does not exist, it will be created. If it exists, the contents will be overwritten (by default).
#include <iostream>#include <fstream>#include <string>
int main() { std::ofstream outFile("example.txt"); if (!outFile.is_open()) { std::cerr << "Error opening file!" << std::endl; return 1; }
outFile << "Hello, world!" << std::endl; outFile << "This is the second line." << std::endl; outFile.close(); std::cout << "Data written." << std::endl; return 0;}Note: we always check if the file was opened successfully and close it after use.
1.2. Reading Data from a File
For reading, we use ifstream. The simplest way is to read line by line using std::getline.
#include <iostream>#include <fstream>#include <string>
int main() { std::ifstream inFile("example.txt"); if (!inFile.is_open()) { std::cerr << "Error opening file!" << std::endl; return 1; }
std::string line; while (std::getline(inFile, line)) { std::cout << line << std::endl; } inFile.close(); return 0;}This method is convenient because it automatically handles the end of the file and does not require additional checks.
1.3. File Opening Modes
You can combine flags to control the opening mode. For example, to append data to the end of a file (append mode), use the std::ios::app flag:
std::ofstream outFile("example.txt", std::ios::app);outFile << "Additional line." << std::endl;outFile.close();Other useful flags: std::ios::binary (binary mode), std::ios::trunc (clear file on opening).
2. Modern File System Work (C++17 and filesystem)
The <filesystem> library greatly simplifies file and folder manipulations. All functions are in the std::filesystem namespace.
2.1. Checking File or Directory Existence
The exists() function returns true if the object exists:
#include <iostream>#include <filesystem>
namespace fs = std::filesystem;
int main() { std::string path = "example.txt"; if (fs::exists(path)) { std::cout << "File exists." << std::endl; } else { std::cout << "File not found." << std::endl; } return 0;}2.2. Creating and Deleting Directories
To create a folder, use create_directory(). To delete, use remove() or remove_all() (recursive deletion).