if is_open return false, do I have to close the file? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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(); }

24th Apr 2017, 11:59 AM
Daniele Gaito
Daniele Gaito - avatar
2 Answers
+ 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?
24th Apr 2017, 1:00 PM
Daniele Gaito
Daniele Gaito - avatar
+ 1
Yes, it is not needed. You can try the code.
27th Apr 2017, 6:40 AM
Gaetano Patria
Gaetano Patria - avatar