Module 23: File HandlingIntermediate45 min read
File Streams (ifstream, ofstream, fstream), Binary Files & File Pointers
Read, write, and append text and binary files safely using <fstream>, RAII file closing, file modes, and seekg/tellg positioning.
Key Takeaways & Core Concepts
- Modes:
std::ios::in,std::ios::out,std::ios::app(append),std::ios::binary.
1. File Streams (`<fstream>`) & Modes
std::ifstream: Input (reading).std::ofstream: Output (writing/truncating).std::fstream: Both reading and writing.- Modes:
std::ios::in,std::ios::out,std::ios::app(append),std::ios::binary.
1. Stream Parsing & seekg Positioning
1#include <iostream>
2#include <sstream>
3#include <string>
4
5int main() {
6 std::stringstream ss("Header:CodeZov");
7 ss.seekg(7); // Jump past "Header:"
8 std::string body;
9 std::getline(ss, body);
10 std::cout << "Body: " << body << "\n";
11 return 0;
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: `seekg(7)` positions the read cursor directly at byte 7.
2. File Pointers & Error Handling
seekg/tellgmove and query the get (read) position;seekp/tellpcontrol the put (write) position.- Always verify
if (!file)orfile.is_open()before I/O, and rely on RAII to close the file automatically.
Practice & AssessmentC++ Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)