0
0
C++programming~5 mins

File open and close operations in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the fstream library in C++?
The fstream library provides classes and functions to perform file input and output operations, such as opening, reading, writing, and closing files.
Click to reveal answer
beginner
How do you open a file for writing in C++?
You create an ofstream object and pass the file name to its constructor or use the open() method. For example: <br>std::ofstream file("example.txt");
Click to reveal answer
beginner
Why is it important to close a file after opening it?
Closing a file releases the system resources associated with it and ensures that all data is properly saved and flushed from buffers to the file.
Click to reveal answer
intermediate
What happens if you try to open a file that does not exist using ifstream?
The file will not open, and the ifstream object will be in a failed state. You can check this using is_open() or by testing the stream in a boolean context.
Click to reveal answer
beginner
Show a simple C++ code snippet to open a file, write "Hello" to it, and then close it.
std::ofstream file("greeting.txt");
if (file.is_open()) {
    file << "Hello";
    file.close();
}
Click to reveal answer
Which C++ class is used to read from a file?
Aiostream
Bofstream
Cifstream
Dfstream
What method do you use to check if a file was successfully opened?
Ais_open()
Bopen()
Cclose()
Dread()
What happens if you forget to close a file after writing?
AData may not be saved properly
BFile is deleted automatically
CProgram crashes immediately
DNothing happens
Which header file must you include to use file streams in C++?
A<cstdio>
B<iostream>
C<fstream.h>
D<fstream>
How do you open a file for both reading and writing?
AUse <code>ifstream</code> only
BUse <code>fstream</code> with appropriate mode flags
CUse <code>ofstream</code> only
DUse <code>iostream</code>
Explain the steps to open a file, write data, and close it in C++.
Think about the order of operations and the classes used.
You got /5 concepts.
    What are the consequences of not closing a file after finishing file operations?
    Consider what happens to data and system resources.
    You got /4 concepts.