+ 6
if is_open return false, do I have to close the file?
In a code like this (from lesson 77), do I have always to close the file, or it could/should be closed only in the positive case? Thanks in advance for your answer. #include <iostream> #include <fstream> using namespace std; int main() { ofstream MyFile("test.txt"); if (MyFile.is_open()) { MyFile << "This is awesome! \n"; } else { cout << "Something went wrong"; } MyFile.close(); }
2 Antworten
+ 7
In the lesson 80 (Challenge 2) I see a similar code, where the file is closed only in positive case.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream MyFile("test.txt");
if (MyFile.is_open()) {
MyFile << "This is awesome! \n";
MyFile.close();
}
else {
cout << "Something went wrong";
}
}
So I think it is not needed to close in negative (else) case the file, is it?
What happen if we close a file not opened?
+ 1
Yes, it is not needed. You can try the code.