There are many ways to open a file. We will discuss some of these in the following sections, and how to accomplish this using the std::fstream C++ APIs.
Opening a file
Different ways to open a file
Opening a file in C++ is as simple as providing a std::fstream object with the filename and path of the object you wish to open. This is shown as follows:
#include <fstream>
#include <iostream>
int main()
{
if (auto file = std::fstream("test.txt")) {
std::cout << "success\n";
}
else {
std::cout << "failure\n";
}
}
// > g++ -std=c++17 scratchpad.cpp; touch test.txt; ./a.out
// success
In this example, we open a file named test.txt, which we previously created...