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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 30 of 45 · C++

Lesson 36: File I/O Streams

Duration: 12 min

File I/O Streams\n\nReading from and writing to files in C++ is performed through the <fstream> library, which provides std::ifstream, std::ofstream, and std::fstream.\n\n---\n\n## Example: Writing a text file\ncpp\n#include <fstream>\n\nint main() {\n std::ofstream out(\"data.txt\");\n if (!out) {\n std::cerr << \"Failed to open file for writing\\n\";\n return 1;\n }\n out << \"Header,Value\\n\";\n for (int i = 0; i < 5; ++i) {\n out << i << \",\" << i * i << '\\n';\n }\n // out is closed automatically when it goes out of scope\n return 0;\n}\n\n\n## Example: Reading the file back in binary mode\ncpp\n#include <fstream>\n#include <vector>\n\nint main() {\n std::ifstream in(\"data.bin\", std::ios::binary);\n if (!in) {\n std::cerr << \"Cannot open file\\n\";\n return 1;\n }\n // Determine file size\n in.seekg(0, std::ios::end);\n std::size_t size = in.tellg();\n in.seekg(0, std::ios::beg);\n std::vector<char> buffer(size);\n in.read(buffer.data(), size);\n std::cout << \"Read \" << size << \" bytes\\n\";\n return 0;\n}\n\n\n> Tip: Use std::filesystem::exists to check file existence before opening.\n\n---\n\n<Alert type="warning">Always verify stream state (if (!stream)) before reading or writing to catch I/O errors early.

Previous: Lesson 35: Exception HandlingNext: Lesson 37: Move Semantics