Concept Flow - File output using ofstream
Create ofstream object
Open file for writing
Write data to file
Close file
End program
This flow shows how a file is opened, written to, and then closed using ofstream in C++.
#include <fstream> int main() { std::ofstream file("output.txt"); file << "Hello, file!\n"; file.close(); return 0; }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create ofstream object with filename "output.txt" | File opened successfully | File ready for writing |
| 2 | Write "Hello, file!\n" to file | Data sent to file buffer | Text written to file |
| 3 | Close the file | File closed | File saved and closed |
| 4 | Return 0 from main | Program ends | Execution complete |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| file | not created | ofstream object opened file | file buffer contains text | file closed | file closed |
ofstream file("filename");
file << "text";
file.close();
- Opens file for writing
- Writes data to file
- Closes file to save data
- Always check if file opened successfully