File output using ofstream in C++ - Time & Space Complexity
When writing data to a file using ofstream, it's important to know how the time taken grows as the amount of data increases.
We want to understand how the program's running time changes when we write more lines to the file.
Analyze the time complexity of the following code snippet.
#include <fstream>
#include <string>
void writeToFile(int n) {
std::ofstream file("output.txt");
for (int i = 0; i < n; ++i) {
file << "Line " << i << "\n";
}
file.close();
}
This code opens a file and writes n lines, each with a line number, then closes the file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing a line to the file inside the loop.
- How many times: The loop runs n times, so the write operation repeats n times.
Each additional line means one more write operation, so the total work grows steadily as n grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes |
| 100 | 100 writes |
| 1000 | 1000 writes |
Pattern observation: The number of operations grows directly in proportion to n.
Time Complexity: O(n)
This means the time to write grows linearly with the number of lines you write.
[X] Wrong: "Writing to a file is instant and does not depend on how many lines we write."
[OK] Correct: Each write takes time, so more lines mean more time. The program does more work as n grows.
Understanding how file writing scales helps you reason about program speed and resource use, a useful skill in many coding tasks.
"What if we buffered multiple lines before writing to the file? How would the time complexity change?"
Practice
ofstream class in C++?Solution
Step 1: Understand the role of
ofstreamofstreamstands for output file stream and is used to write data to files.Step 2: Differentiate from other stream classes
Unlikeifstreamwhich reads files,ofstreamis specifically for output (writing).Final Answer:
To write data to files -> Option DQuick Check:
ofstream= write files [OK]
- Confusing ofstream with ifstream
- Thinking ofstream reads files
- Assuming ofstream manages memory
data.txt for writing using ofstream?Solution
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.Step 2: Analyze each option
std::ofstream file("data.txt"); usesstd::ofstream file("data.txt");which is correct syntax. Others misuse assignment or method calls.Final Answer:
std::ofstream file("data.txt"); -> Option AQuick Check:
Constructor with filename opens file [OK]
- Using assignment instead of constructor
- Calling open() as if it returns a value
- Incorrect syntax for open method
output.txt after running this code?std::ofstream file("output.txt");
if (file.is_open()) {
file << "Hello" << std::endl;
file << "World";
file.close();
}Solution
Step 1: Understand what is written to the file
The first line writes "Hello" followed by a newline because ofstd::endl. The second line writes "World" without newline.Step 2: Combine the written content
So the file content is "Hello" + newline + "World" with no extra newline after "World".Final Answer:
Hello\nWorld -> Option AQuick Check:
endl adds newline only after Hello [OK]
- Assuming std::endl adds two newlines
- Thinking last line adds newline
- Confusing order of output
std::ofstream file;
file << "Test";
file.open("test.txt");
file.close();Solution
Step 1: Check order of operations
The code tries to write to the file before opening it, which is invalid.Step 2: Understand consequences
Writing before opening means no file is ready, so output fails silently or causes error.Final Answer:
File is opened after writing, so output fails -> Option CQuick Check:
Open file before writing [OK]
- Writing before opening file
- Forgetting to check if file opened
- Closing file before writing
lines to a file log.txt. Which code snippet correctly opens the file, writes all lines with newlines, and closes the file safely?Solution
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.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.Final Answer:
std::ofstream file("log.txt");\nfor (auto line : lines) file << line << "\n";\nfile.close(); -> Option BQuick Check:
Open file first, write lines with newlines, then close [OK]
- Writing before opening file
- Forgetting newlines after each line
- Not closing the file
Ready to prove it?
Pass the test and this pattern moves unknown
