Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 36: File I/O Streams | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 36 of 45

·C++

Lesson 36: File I/O Streams

12 min

Course progress80%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Opening files with std::ifstream / std::ofstream
  • Binary vs. text mode
  • Error handling with stream state flags
  • Using std::filesystem for path operations

File I/O Streams

Reading from and writing to files in C++ is performed through the <fstream> library, which provides std::ifstream, std::ofstream, and std::fstream.


Example: Writing a text file

#include <fstream>

int main() {
    std::ofstream out(\"data.txt\");
    if (!out) {
        std::cerr << \"Failed to open file for writing\
\";
        return 1;
    }
    out << \"Header,Value\
\";
    for (int i = 0; i < 5; ++i) {
        out << i << \",\" << i * i << '\
';
    }
    // out is closed automatically when it goes out of scope
    return 0;
}

Example: Reading the file back in binary mode

#include <fstream>
#include <vector>

int main() {
    std::ifstream in(\"data.bin\", std::ios::binary);
    if (!in) {
        std::cerr << \"Cannot open file\
\";
        return 1;
    }
    // Determine file size
    in.seekg(0, std::ios::end);
    std::size_t size = in.tellg();
    in.seekg(0, std::ios::beg);
    std::vector<char> buffer(size);
    in.read(buffer.data(), size);
    std::cout << \"Read \" << size << \" bytes\
\";
    return 0;
}

Tip: Use std::filesystem::exists to check file existence before opening.


<Alert type="warning">Always verify stream state (if (!stream)) before reading or writing to catch I/O errors early.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 35: Exception HandlingContinue to lesson 37Lesson 37: Move SemanticsBack to C++ Course curriculum