Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to open a file named "data.txt" for reading.
C++
#include <fstream> int main() { std::ifstream file; file.[1]("data.txt"); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'close' instead of 'open' to start file access.
Trying to use 'read' or 'write' directly without opening the file.
β Incorrect
The open function is used to open a file stream in C++.
2fill in blank
mediumComplete the code to check if the file was successfully opened.
C++
#include <fstream> #include <iostream> int main() { std::ifstream file("data.txt"); if (!file.[1]()) { std::cout << "Failed to open file." << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'open()' instead of 'is_open()' to check file status.
Using 'fail()' which checks for failure but not specifically if open.
β Incorrect
The is_open() function returns true if the file is open.
3fill in blank
hardFix the error in closing the file stream.
C++
#include <fstream> int main() { std::ofstream file("output.txt"); // Write something to file file << "Hello!"; file.[1](); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'open()' to close the file.
Using 'flush()' which only clears buffers but does not close.
β Incorrect
The close() function properly closes the file stream.
4fill in blank
hardFill both blanks to open a file for writing and check if it opened successfully.
C++
#include <fstream> #include <iostream> int main() { std::ofstream file; file.[1]("log.txt"); if (!file.[2]()) { std::cout << "Cannot open file." << std::endl; } return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using 'close' instead of 'open' to open the file.
Using 'fail' instead of 'is_open' to check file status.
β Incorrect
Use open() to open the file and is_open() to check if it opened.
5fill in blank
hardFill all three blanks to open a file, write "Test" to it, and then close it.
C++
#include <fstream> int main() { std::ofstream file; file.[1]("test.txt"); file << [2]; file.[3](); return 0; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Forgetting to open the file before writing.
Not closing the file after writing.
β Incorrect
Open the file with open(), write the string "Test", then close with close().