File_Handling
File_Handling
File handling in C++ refers to creating, opening, reading, writing, and closing files using standard
Classes Used:
Include header:
#include <fstream>
File Operations
Writing to a File
#include <fstream>
int main() {
ofstream file("sample.txt");
file.close();
return 0;
}
#include <fstream>
#include <iostream>
int main() {
ifstream file("sample.txt");
string content;
file.close();
return 0;
#include <fstream>
#include <iostream>
int main() {
fstream file;
file.seekg(0);
string line;
file.close();
else {
return 0;
Mode | Purpose
--------------|----------------------------------
#include <iostream>
#include <fstream>
class Student {
public:
string name;
int roll;
void input() {
void show() {
cout << "Name: " << name << ", Roll No: " << roll << endl;
};
int main() {
Student s;
int choice;
do {
cout << "\n1. Add Record\n2. Display Records\n3. Exit\nEnter choice: ";
if (choice == 1) {
s.input();
file << s.name << " " << s.roll << endl;
file.close();
else if (choice == 2) {
ifstream file("students.txt");
s.show();
file.close();
return 0;
Important Points
Advanced Project: Student Management System (Add, View, Update, Delete) Using File Handling in
C++
Let's now extend our mini project into a full Student Management System with the following
functionalities: