Lesson 11
File I/O in C++
Read and write files with streams
1What is File I/O?✨
File Input/Output (I/O) allows you to read from and write to files in C++. This is essential for saving data, logging information, and handling larger datasets.
2Why Learn File I/O?🎯
- ✓ Store user data permanently
- ✓ Read configurations from files
- ✓ Handle large volumes of data efficiently
- ✓ Create applications with persistent storage
3Reading from a File💡
💻 code
To read from a file, you use an `ifstream` (input file stream). Here's how you can read a simple text file:💻 code
#include <iostream>
#include <fstream>
#include <string>💻 code
int main() {
std::ifstream inputFile("data.txt");
std::string line;💻 code
if (inputFile.is_open()) {
while (getline(inputFile, line)) {
std::cout << line << std::endl;
}
inputFile.close();
} else {
std::cout << "Unable to open file";
}💻 code
return 0;
}4Writing to a File🚀
💻 code
To write to a file, you can use an `ofstream` (output file stream). Here's a basic example:💻 code
#include <iostream>
#include <fstream>💻 code
int main() {
std::ofstream outputFile("output.txt");💻 code
if (outputFile.is_open()) {
outputFile << "Hello, File!\n";
outputFile << "This is a line of text.\n";
outputFile.close();
} else {
std::cout << "Unable to open file";
}💻 code
return 0;
}5File I/O Operations🔍
- You can perform various operations with files:
- Checking if the file is open
- Reading line by line or word by word
- Writing data in different formats
- Appending data to existing files
6Best Practices⭐
- When working with files, keep these tips in mind:
- ✓ Always check if the file opened successfully
- ✓ Close the file after operations to free resources
- ✓ Handle exceptions for better error management
7What You'll Build This Grade🧩
- ✓ Programs that save user preferences
- ✓ Applications that read and analyze data
- ✓ Games that save progress in files
- ✓ Tools that log events to a file
🎯 Practice Challenges
Master File I/O in C++ by completing all 3 difficulty levels
🟢 EASY
File I/O in C++ - Easy Challenge
Start with the basics. Perfect for beginners!
🟡 MEDIUM
File I/O in C++ - Medium Challenge
Get more challenging. Build your confidence!
🔴 HARD
File I/O in C++ - Hard Challenge
Master this concept. Prove your skills!
🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →
Ready to Master File I/O in C++? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 10: Exception Handling in C++try, catch, and throw
- Next lesson →Lesson 12: Vectors & IteratorsMaster dynamic arrays
- Grade 12 courseDatabases - Data Management MasterSQL coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 11 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.