Bird
Raised Fist0
C++programming~20 mins

File output using ofstream in C++ - Practice Problems & Coding Challenges

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

Consider the following C++ code that writes to a file using ofstream. What will be the content of the file output.txt after running this program?

C++
#include <fstream>
#include <string>

int main() {
    std::ofstream file("output.txt");
    file << "Hello" << std::endl;
    file << "World" << std::endl;
    file.close();
    return 0;
}
A"Hello\nWorld\n"
B"HelloWorld"
C"Hello World"
D"Hello\nWorld"
Attempts:
2 left
πŸ’‘ Hint

Remember that std::endl inserts a newline character and flushes the stream.

❓ Predict Output
intermediate
2:00remaining
What happens if the file cannot be opened?

What will be the output of this program if the file /root/secret.txt cannot be opened due to permission issues?

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

int main() {
    std::ofstream file("/root/secret.txt");
    if (!file) {
        std::cout << "Failed to open file" << std::endl;
    } else {
        file << "Data" << std::endl;
    }
    return 0;
}
AFailed to open file
BData
CCompilation error
DNo output
Attempts:
2 left
πŸ’‘ Hint

Check how the program tests if the file stream is valid.

πŸ”§ Debug
advanced
2:00remaining
Why does this code not write anything to the file?

The following code is supposed to write "Test" to log.txt, but the file remains empty. What is the reason?

C++
#include <fstream>

int main() {
    std::ofstream file;
    file << "Test";
    file.close();
    return 0;
}
AThe program lacks write permissions
BThe file stream was not closed properly
CThe file was never opened before writing
DThe file path is incorrect
Attempts:
2 left
πŸ’‘ Hint

Check how the ofstream object is created and used.

🧠 Conceptual
advanced
2:00remaining
What is the effect of opening a file with std::ofstream in append mode?

What happens when you open a file with std::ofstream file("data.txt", std::ios::app); and write data to it?

AThe existing file content is erased before writing
BThe file is locked and cannot be written
CThe file is opened in read-only mode
DNew data is added at the end of the existing file content
Attempts:
2 left
πŸ’‘ Hint

Think about what append mode means for files.

πŸ“ Syntax
expert
3:00remaining
Which option correctly opens a file for writing and checks for errors?

Choose the code snippet that correctly opens a file named report.txt for writing using ofstream and checks if the file was opened successfully.

A
#include &lt;fstream&gt;

int main() {
    std::ofstream file("report.txt");
    if (!file.is_open()) {
        return 1;
    }
    file &lt;&lt; "Report data";
    file.close();
    return 0;
}
B
#include &lt;fstream&gt;

int main() {
    std::ofstream file;
    file.open("report.txt");
    if (!file) {
        return 1;
    }
    file &lt;&lt; "Report data";
    file.close();
    return 0;
}
C
#include &lt;fstream&gt;

int main() {
    std::ofstream file;
    file.open("report.txt");
    if (file == nullptr) {
        return 1;
    }
    file &lt;&lt; "Report data";
    file.close();
    return 0;
}
D
#include &lt;fstream&gt;

int main() {
    std::ofstream file("report.txt");
    if (file == NULL) {
        return 1;
    }
    file &lt;&lt; "Report data";
    file.close();
    return 0;
}
Attempts:
2 left
πŸ’‘ Hint

Check how to test if an ofstream is open and valid.

Practice

(1/5)
1. What is the primary purpose of the ofstream class in C++?
easy
A. To manage memory allocation
B. To read data from files
C. To create graphical user interfaces
D. To write data to files

Solution

  1. Step 1: Understand the role of ofstream

    ofstream stands for output file stream and is used to write data to files.
  2. Step 2: Differentiate from other stream classes

    Unlike ifstream which reads files, ofstream is specifically for output (writing).
  3. Final Answer:

    To write data to files -> Option D
  4. Quick Check:

    ofstream = write files [OK]
Hint: Remember 'o' in ofstream means output (write) [OK]
Common Mistakes:
  • Confusing ofstream with ifstream
  • Thinking ofstream reads files
  • Assuming ofstream manages memory
2. Which of the following is the correct way to open a file named data.txt for writing using ofstream?
easy
A. std::ofstream file("data.txt");
B. std::ofstream file.open("data.txt");
C. std::ofstream file = "data.txt";
D. std::ofstream file.open = "data.txt";

Solution

  1. Step 1: Recall correct syntax for opening file with ofstream

    The correct way is to create an ofstream object and pass the filename as a constructor argument.
  2. Step 2: Analyze each option

    std::ofstream file("data.txt"); uses std::ofstream file("data.txt"); which is correct syntax. Others misuse assignment or method calls.
  3. Final Answer:

    std::ofstream file("data.txt"); -> Option A
  4. Quick Check:

    Constructor with filename opens file [OK]
Hint: Use constructor with filename to open file [OK]
Common Mistakes:
  • Using assignment instead of constructor
  • Calling open() as if it returns a value
  • Incorrect syntax for open method
3. What will be the content of the file output.txt after running this code?
std::ofstream file("output.txt");
if (file.is_open()) {
  file << "Hello" << std::endl;
  file << "World";
  file.close();
}
medium
A. Hello\nWorld
B. HelloWorld
C. Hello\nWorld\n
D. World\nHello

Solution

  1. Step 1: Understand what is written to the file

    The first line writes "Hello" followed by a newline because of std::endl. The second line writes "World" without newline.
  2. Step 2: Combine the written content

    So the file content is "Hello" + newline + "World" with no extra newline after "World".
  3. Final Answer:

    Hello\nWorld -> Option A
  4. Quick Check:

    endl adds newline only after Hello [OK]
Hint: Remember std::endl adds newline, << just appends text [OK]
Common Mistakes:
  • Assuming std::endl adds two newlines
  • Thinking last line adds newline
  • Confusing order of output
4. Identify the error in this code snippet that writes to a file:
std::ofstream file;
file << "Test";
file.open("test.txt");
file.close();
medium
A. Missing #include <fstream>
B. File is never closed
C. File is opened after writing, so output fails
D. File is opened twice

Solution

  1. Step 1: Check order of operations

    The code tries to write to the file before opening it, which is invalid.
  2. Step 2: Understand consequences

    Writing before opening means no file is ready, so output fails silently or causes error.
  3. Final Answer:

    File is opened after writing, so output fails -> Option C
  4. Quick Check:

    Open file before writing [OK]
Hint: Always open file before writing [OK]
Common Mistakes:
  • Writing before opening file
  • Forgetting to check if file opened
  • Closing file before writing
5. You want to write multiple lines from a vector of strings lines to a file log.txt. Which code snippet correctly opens the file, writes all lines with newlines, and closes the file safely?
hard
A. std::ofstream file; file.open("log.txt"); for (int i = 0; i < lines.size(); i++) file << lines[i]; file.close();
B. std::ofstream file("log.txt"); for (auto line : lines) file << line << "\n"; file.close();
C. std::ofstream file("log.txt"); for (auto line : lines) file << line; file.close();
D. std::ofstream file; for (auto line : lines) file << line << "\n"; file.open("log.txt"); file.close();

Solution

  1. Step 1: Check file opening and writing order

    std::ofstream file("log.txt"); for (auto line : lines) file << line << "\n"; file.close(); opens the file at construction, then writes each line with a newline, then closes the file.
  2. Step 2: Compare other options

    std::ofstream file; file.open("log.txt"); for (int i = 0; i < lines.size(); i++) file << lines[i]; file.close(); writes without newlines; std::ofstream file("log.txt"); for (auto line : lines) file << line; file.close(); writes without newlines; std::ofstream file; for (auto line : lines) file << line << "\n"; file.open("log.txt"); file.close(); writes before opening file, which is wrong.
  3. Final Answer:

    std::ofstream file("log.txt");\nfor (auto line : lines) file << line << "\n";\nfile.close(); -> Option B
  4. Quick Check:

    Open file first, write lines with newlines, then close [OK]
Hint: Open file first, write lines with \n, then close [OK]
Common Mistakes:
  • Writing before opening file
  • Forgetting newlines after each line
  • Not closing the file
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