I have read several reference articles regarding file IO, and about opening files in particular, but nowhere found any info about how to distinguish (with combinations of open mode flags) between the cases when file should be created if not exist during opening, and when function must fail if the file doesn't exist. Could someone quote the link where this is described.
Instead of fstream I find it easier to use ofstream when writing (creating) files and ifstream when reading from files.
If you use ofstream it will automatically create a new file if it doesn't exist.
1 2 3 4 5 6 7 8 9
#include <fstream>
int main()
{
std::ofstream file("test.txt");
// For text files you write output the same way as with std::cout.
file << "Hello 123!\n";
}
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream file("test.txt");
if (!file)
{
std::cout << "File not found!";
return 1;
}
// For text files you read input the same way as with std::cin.
std::string line;
while (std::getline(file, line))
{
std::cout << line << '\n';
}
}
Many thanks, Peter. Of course internet search returns plenty of links on programming forums and stack overflow with users' advises on this subject. I wonder where this is described in official docs or in reference articles on this site?