Bird
Raised Fist0
C++programming~20 mins

File open and close operations in C++ - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
File Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this file operation code?

Consider the following C++ code that opens a file, writes to it, and then closes it. What will be the output printed on the console?

C++
#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("test.txt");
    if (!file.is_open()) {
        std::cout << "Failed to open file" << std::endl;
        return 1;
    }
    file << "Hello, file!" << std::endl;
    file.close();
    if (file.is_open()) {
        std::cout << "File is still open" << std::endl;
    } else {
        std::cout << "File closed successfully" << std::endl;
    }
    return 0;
}
AFile closed successfully
BFailed to open file
CFile is still open
DNo output
Attempts:
2 left
πŸ’‘ Hint

Check what file.is_open() returns after closing the file.

🧠 Conceptual
intermediate
1:30remaining
Which statement about file closing is true?

In C++, what happens if you do not explicitly call close() on an ofstream object before the program ends?

AThe file remains open and data is lost
BThe program will crash due to an unclosed file
CThe file is automatically closed when the <code>ofstream</code> object is destroyed
DThe file is deleted from the disk
Attempts:
2 left
πŸ’‘ Hint

Think about what happens to objects when they go out of scope.

πŸ”§ Debug
advanced
2:30remaining
Why does this code fail to write to the file?

Examine the following code snippet. It attempts to write "Hello" to a file but the file remains empty. What is the cause?

C++
#include <fstream>

int main() {
    std::ofstream file;
    file << "Hello";
    file.open("output.txt");
    file.close();
    return 0;
}
AThe file is closed before opening
BThe file is not opened at all
CThe file is opened in read mode only
DThe file is opened after writing, so data is not saved
Attempts:
2 left
πŸ’‘ Hint

Check the order of operations: when is the file opened vs when is data written?

πŸ“ Syntax
advanced
2:00remaining
Which option will cause a compilation error?

Which of the following code snippets will cause a compilation error when trying to open a file for writing?

Astd::ofstream file("data.txt");
Bstd::ifstream file("data.txt"); file << "Hello";
Cstd::ofstream file; file.open("data.txt");
Dstd::ofstream file; file.open("data.txt", std::ios::out);
Attempts:
2 left
πŸ’‘ Hint

Consider which stream type supports writing with the << operator.

πŸš€ Application
expert
3:00remaining
How many times is the file opened in this code?

Analyze the following code. How many times is the file "log.txt" opened during execution?

C++
#include <fstream>

void writeLog() {
    std::ofstream file("log.txt", std::ios::app);
    file << "Log entry\n";
}

int main() {
    for (int i = 0; i < 3; ++i) {
        writeLog();
    }
    return 0;
}
A3
B0
C1
D6
Attempts:
2 left
πŸ’‘ Hint

Consider how many times the function writeLog() is called and what happens inside it.

Practice

(1/5)
1. What is the primary purpose of the open() function in C++ file handling?
easy
A. To start using a file for reading or writing
B. To close a file after use
C. To delete a file from the system
D. To rename a file

Solution

  1. Step 1: Understand the role of open()

    The open() function is used to start using a file by opening it for reading or writing.
  2. Step 2: Differentiate from other file operations

    Closing a file is done by close(), deleting or renaming files are not done by open().
  3. Final Answer:

    To start using a file for reading or writing -> Option A
  4. Quick Check:

    open() = start file use [OK]
Hint: Remember: open() starts file access, close() ends it [OK]
Common Mistakes:
  • Confusing open() with close()
  • Thinking open() deletes files
  • Assuming open() renames files
2. Which of the following is the correct syntax to **explicitly** open a file named "data.txt" for writing using an ofstream object named file?
easy
A. file.open("data.txt", ios::in);
B. file.open("data.txt");
C. file.close("data.txt");
D. file.open("data.txt", ios::out);

Solution

  1. Step 1: Identify the correct mode for writing

    To open a file for writing, use ios::out mode with open().
  2. Step 2: Check syntax correctness

    file.open("data.txt", ios::out); correctly opens the file for writing. file.open("data.txt", ios::in); uses ios::in which is for reading. file.open("data.txt"); opens without mode, which defaults to reading for ifstream, but for ofstream it defaults to writing, but explicit mode is better. file.close("data.txt"); is incorrect syntax for closing.
  3. Final Answer:

    file.open("data.txt", ios::out); -> Option D
  4. Quick Check:

    Writing mode = ios::out [OK]
Hint: Use ios::out to open files for writing [OK]
Common Mistakes:
  • Using ios::in instead of ios::out for writing
  • Calling close() instead of open()
  • Omitting mode when explicit mode is needed
3. Assuming "example.txt" exists, what will be the output of the following C++ code snippet?
std::ifstream file;
file.open("example.txt");
if (!file) {
    std::cout << "File not opened";
} else {
    std::cout << "File opened successfully";
}
file.close();
medium
A. File not opened
B. File opened successfully
C. Compilation error
D. No output

Solution

  1. Step 1: Understand file opening check

    The code opens "example.txt" for reading. The if (!file) checks if the file failed to open.
  2. Step 2: Assume file exists and opens

    If "example.txt" exists and is accessible, file is valid, so the else block runs printing "File opened successfully".
  3. Final Answer:

    File opened successfully -> Option B
  4. Quick Check:

    File open check prints success if file opens [OK]
Hint: Check file with if(!file) after open() to confirm success [OK]
Common Mistakes:
  • Assuming file always fails to open
  • Confusing syntax of if(!file)
  • Forgetting to close the file
4. Identify the error in the following code snippet:
std::ofstream file;
file.open("output.txt");
file << "Hello, world!";
// Missing file.close();
medium
A. File is not closed after writing
B. Cannot write to file opened with ofstream
C. Syntax error in file.open()
D. File is not opened before writing

Solution

  1. Step 1: Check file opening and writing

    The file is opened correctly with file.open("output.txt") and data is written using <<.
  2. Step 2: Identify missing file closing

    The code does not call file.close(), which is important to flush data and release the file resource.
  3. Final Answer:

    File is not closed after writing -> Option A
  4. Quick Check:

    Always close files after writing [OK]
Hint: Always call close() after writing to save data properly [OK]
Common Mistakes:
  • Forgetting to close the file
  • Thinking file closes automatically immediately
  • Confusing open() syntax
5. You want to read from a file "data.txt" and write its contents to "backup.txt" in C++. Which sequence of operations is correct?
hard
A. Open "data.txt" with ofstream, open "backup.txt" with ifstream, write to first, read from second, close both files
B. Open both files with ifstream, read from both, close both files
C. Open "data.txt" with ifstream, open "backup.txt" with ofstream, read from first, write to second, close both files
D. Open both files with ofstream, write to both, close both files

Solution

  1. Step 1: Identify correct stream types for reading and writing

    Use ifstream to read from "data.txt" and ofstream to write to "backup.txt".
  2. Step 2: Follow correct operation order

    Open both files, read from the input file, write to the output file, then close both files to save changes and release resources.
  3. Final Answer:

    Open "data.txt" with ifstream, open "backup.txt" with ofstream, read from first, write to second, close both files -> Option C
  4. Quick Check:

    ifstream for reading, ofstream for writing [OK]
Hint: Use ifstream to read, ofstream to write, then close files [OK]
Common Mistakes:
  • Mixing up ifstream and ofstream
  • Not closing files after operations
  • Trying to write with ifstream or read with ofstream
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard