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?
✗ Incorrect
The
ifstream class is used specifically for reading from files.What method do you use to check if a file was successfully opened?
✗ Incorrect
The
is_open() method returns true if the file is open.What happens if you forget to close a file after writing?
✗ Incorrect
Not closing a file can cause data to remain in buffers and not be saved to disk.
Which header file must you include to use file streams in C++?
✗ Incorrect
The standard header for file streams is
<fstream>.How do you open a file for both reading and writing?
✗ Incorrect
The
fstream class can open files for both reading and writing by specifying mode flags.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.