0
0
C++programming~10 mins

File open and close operations in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Aclose
Bopen
Cread
Dwrite
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.
2fill in blank
medium

Complete 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'
Aclose
Bopen
Cis_open
Dfail
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.
3fill in blank
hard

Fix 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'
Awrite
Bflush
Copen
Dclose
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'open()' to close the file.
Using 'flush()' which only clears buffers but does not close.
4fill in blank
hard

Fill 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'
Aopen
Bclose
Cis_open
Dfail
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.
5fill in blank
hard

Fill 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'
Aopen
B"Test"
Cclose
Dwrite
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Forgetting to open the file before writing.
Not closing the file after writing.