So I have the following code:
#include <iostream>
#include <fstream>
#include <string>
void writeSingle(std::fstream &myFileStream)
{
myFileStream.open("my_file2", std::ios::trunc);
if (!myFileStream)
{
std::cout << "File not created!\n";
}
else
{
std::cout << "File created successfully!\n";
myFileStream << "Line 1\n";
myFileStream << "Line 2\n";
myFileStream << "Line 3\n";
myFileStream.close();
}
}
int main()
{
std::fstream myFileStream;
writeSingle(myFileStream);
return 0;
}
My question is, whenever I use std::ios::trunc, be it in a combination with app (std::ios::trunc | std::ios::app) and regardless to whether the file exists or not, the program
ends up in the !myFileStream block. With only std::ios::out and std::ios::app the program works as expected.
Why is it so? Can someone provide at least one working example with std::ios::trunc?
Thanks.