SlideShare a Scribd company logo
1 of 6
File Operations using ifstream and ofstream
This is a simple File Handling Program in C++ for writing and reading a
file using streams.
#include<iostream.h>
#include<fstream.h>
#include<math.h>
void main()
{
Clrscr ();
ofstream fout("Myfile");
fout<<"ali";
fout.close();
ifstream fin("Myfile");
char ch;
while(fin)
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
}
Hello world program writing into a file
First step
Open a file for writing :
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream ofile; // declaring an object of class ofstream
ofile.open("file.txt"); // open "file.txt" for writing data
cout << "Data written to file" << endl;
ofile.close(); // close the file
return 0;
}
Copy to clipb
Step 2 [program]
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
Char str[10];
Ofstream out(“cfile.text”);
cout<<”Hello world”;
out.close();
}
Open a file for reading :
#include<iostream>
#include<fstream>
using namespace std;
int main() {
char str[10]; // buffer to store a line read from file
ofstream file(“cfile.text”);
While (!in.eof())
{
in.getline(str, 10);
}
in.close();
return 0;
}
Copy to clipb
In the first program, a file “ file.txt ” is created and some data is written into it. The file is created in the same
directory in which the program file is saved.
In the second program, we read the file line by line using and then print each line on the console. The while loop
continues till the end of file is reached. We ensure that using the condition while( ! in.eof( ) ). Note that we can
simply use while( ofile )also.
We can open a file using the constructors of ifstream and ofstream classes instead of using open( ) member
function. For e.g, ofstream file( “file.text” );. It is a good practice to check if file is opened successfully before
proceeding with further operations.
File Operations using fstream
Open a file and append data to the end of the file :
#include<iostream>
#include<fstream>
using namespace std;
int main() {
char line[100];
fstream file; // declare an object of fstream class
file.open("file.txt", ios :: out | ios :: app); // open file in append mode
if (file.fail())
{ // check if file is opened successfully
// file opening failed
cout << "Error Opening file ... " << endl;
}
else {
// proceed with further operations
cout << "Enter a line : ";
cin.getline(line, 100);
file << line << endl; // Append the line to the file
cout << "Line written into the file" << endl;
}
return 0;
}
Copy to clipb
Open the file for reading :
#include<iostream>
#include<fstream>
using namespace std;
int main() {
char line[100];
fstream file; // declare an object of fstream class
file.open("file.txt", ios :: out | ios :: app); // open file in append mode
if (file.fail())
{ // check if file is opened successfully
// file opening failed
cout << "Error Opening file ... " << endl;
}
else {
// proceed with further operations
cout << "Enter a line : ";
cin.getline(line, 100);
file << line << endl; // Append the line to the file
cout << "Line written into the file" << endl;
}
return 0;
}
Copy to clipb
In the first program, we take a line as input from user and appends that line to the “ file.txt “.
In the second program, we read the file character by character using get( ) function. Similarly, we can write a
single character to a file using put function.
Writing class objects to a file
There are member functions read( ) and write( ) in the fstream class which allows reading and writing of class
objects. These functions can also be used to write array elements into the file. See the program below :
#include<iostream>
#include<fstream>
using namespace std;
// define a class to store student data
class student {
int roll;
char name[30];
float marks;
public:
student() { }
void getData(); // get student data from user
void displayData(); // display data
};
void student :: getData() {
cout << "nEnter Roll No. : ";
cin >> roll;
cin.ignore(); // ignore the newline char inserted when you press enter
cout << "Enter Name : ";
cin.getline(name, 30);
cout << "Enter Marks : ";
cin >> marks;
}
void student :: displayData() {
cout << "nRoll No. : " << roll << endl;
cout << "Name : " << name << endl;
cout << "Marks : " << marks << endl;
}
int main() {
student s[3]; // array of 3 student objects
fstream file;
int i;
file.open("objects.txt", ios :: out); // open file for writing
cout << "nWriting Student information to the file :- " << endl;
for (i = 0; i < 3; i++) {
s[i].getData();
// write the object to a file
file.write((char *)&s[i], sizeof(s[i]));
}
file.close(); // close the file
file.open("objects.txt", ios :: in); // open file for reading
cout << "nReading Student information to the file :- " << endl;
for (i = 0; i < 3; i++) {
// read an object from a file
file.read((char *)&s[i], sizeof(s[i]));
s[i].displayData();
}
file.close(); // close the file
return 0;
}
Whenever we are taking input from console, we press “enter” key. This leads to a newline character being insert
ed in the input buffer. cin ignores this character to take further inputs but cin.getline( ) doesn’t ignore it. Thus, w
e need to use the function cin.ignore( ) otherwise, we won’t be able to take further inputs.
JazakAllah

More Related Content

What's hot

Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi Vipin sharma
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHPThomas Weinert
 
Node.js - iJS 2019
Node.js - iJS 2019Node.js - iJS 2019
Node.js - iJS 2019NilsMehlhorn
 
Exp 6.3 d-422 (2)
Exp 6.3 d-422  (2)Exp 6.3 d-422  (2)
Exp 6.3 d-422 (2)Omkar Rane
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesThomas Weinert
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!David Sanchez
 
Plone Conference 2008 Lightning Talk Static Zope Rpx
Plone Conference 2008 Lightning Talk Static Zope RpxPlone Conference 2008 Lightning Talk Static Zope Rpx
Plone Conference 2008 Lightning Talk Static Zope RpxParis, France
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flowkang taehun
 

What's hot (19)

Php file handling in Hindi
Php file handling in Hindi Php file handling in Hindi
Php file handling in Hindi
 
Php i basic chapter 4
Php i basic chapter 4Php i basic chapter 4
Php i basic chapter 4
 
Fileinc
FileincFileinc
Fileinc
 
Linux basic1&amp;2
Linux basic1&amp;2Linux basic1&amp;2
Linux basic1&amp;2
 
PHP pod mikroskopom
PHP pod mikroskopomPHP pod mikroskopom
PHP pod mikroskopom
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHP
 
Node.js - iJS 2019
Node.js - iJS 2019Node.js - iJS 2019
Node.js - iJS 2019
 
Exp 6.3 d-422 (2)
Exp 6.3 d-422  (2)Exp 6.3 d-422  (2)
Exp 6.3 d-422 (2)
 
Git avançado
Git avançadoGit avançado
Git avançado
 
Functional php
Functional phpFunctional php
Functional php
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard Interfaces
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!
 
Plone Conference 2008 Lightning Talk Static Zope Rpx
Plone Conference 2008 Lightning Talk Static Zope RpxPlone Conference 2008 Lightning Talk Static Zope Rpx
Plone Conference 2008 Lightning Talk Static Zope Rpx
 
Javascript Execution Context Flow
Javascript Execution Context FlowJavascript Execution Context Flow
Javascript Execution Context Flow
 
P5
P5P5
P5
 
Files in c++
Files in c++Files in c++
Files in c++
 
Python IO
Python IOPython IO
Python IO
 

Similar to Exmaples of file handling

Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-fileDeepak Singh
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxRutujaTandalwade
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptxradhushri
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 
Files in c
Files in cFiles in c
Files in cTanujaA3
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.pptHEMAHEMS5
 
hasbngclic687.ppt
hasbngclic687.ppthasbngclic687.ppt
hasbngclic687.pptHEMAHEMS5
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ pptKumar
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
Write a program that asks the user for the name of a file. The progra.docx
 Write a program that asks the user for the name of a file. The progra.docx Write a program that asks the user for the name of a file. The progra.docx
Write a program that asks the user for the name of a file. The progra.docxajoy21
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 

Similar to Exmaples of file handling (20)

Chpater29 operation-on-file
Chpater29 operation-on-fileChpater29 operation-on-file
Chpater29 operation-on-file
 
File & Exception Handling in C++.pptx
File & Exception Handling in C++.pptxFile & Exception Handling in C++.pptx
File & Exception Handling in C++.pptx
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
file handling final3333.pptx
file handling final3333.pptxfile handling final3333.pptx
file handling final3333.pptx
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Files in c++
Files in c++Files in c++
Files in c++
 
working with files
working with filesworking with files
working with files
 
Files in c
Files in cFiles in c
Files in c
 
csc1201_lecture13.ppt
csc1201_lecture13.pptcsc1201_lecture13.ppt
csc1201_lecture13.ppt
 
hasbngclic687.ppt
hasbngclic687.ppthasbngclic687.ppt
hasbngclic687.ppt
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
file handling c++
file handling c++file handling c++
file handling c++
 
Write a program that asks the user for the name of a file. The progra.docx
 Write a program that asks the user for the name of a file. The progra.docx Write a program that asks the user for the name of a file. The progra.docx
Write a program that asks the user for the name of a file. The progra.docx
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
C Programming Project
C Programming ProjectC Programming Project
C Programming Project
 

Recently uploaded

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 

Recently uploaded (20)

Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 

Exmaples of file handling

  • 1. File Operations using ifstream and ofstream This is a simple File Handling Program in C++ for writing and reading a file using streams. #include<iostream.h> #include<fstream.h> #include<math.h> void main() { Clrscr (); ofstream fout("Myfile"); fout<<"ali"; fout.close(); ifstream fin("Myfile"); char ch; while(fin) { fin.get(ch); cout<<ch; } fin.close(); getch(); } Hello world program writing into a file First step Open a file for writing : #include<iostream> #include<fstream> using namespace std; int main() { ofstream ofile; // declaring an object of class ofstream ofile.open("file.txt"); // open "file.txt" for writing data cout << "Data written to file" << endl; ofile.close(); // close the file return 0; } Copy to clipb Step 2 [program] #include<iostream> #include<fstream>
  • 2. using namespace std; int main() { Char str[10]; Ofstream out(“cfile.text”); cout<<”Hello world”; out.close(); } Open a file for reading : #include<iostream> #include<fstream> using namespace std; int main() { char str[10]; // buffer to store a line read from file ofstream file(“cfile.text”); While (!in.eof()) { in.getline(str, 10); } in.close(); return 0; } Copy to clipb In the first program, a file “ file.txt ” is created and some data is written into it. The file is created in the same directory in which the program file is saved. In the second program, we read the file line by line using and then print each line on the console. The while loop continues till the end of file is reached. We ensure that using the condition while( ! in.eof( ) ). Note that we can
  • 3. simply use while( ofile )also. We can open a file using the constructors of ifstream and ofstream classes instead of using open( ) member function. For e.g, ofstream file( “file.text” );. It is a good practice to check if file is opened successfully before proceeding with further operations. File Operations using fstream Open a file and append data to the end of the file : #include<iostream> #include<fstream> using namespace std; int main() { char line[100]; fstream file; // declare an object of fstream class file.open("file.txt", ios :: out | ios :: app); // open file in append mode if (file.fail()) { // check if file is opened successfully // file opening failed cout << "Error Opening file ... " << endl; } else { // proceed with further operations cout << "Enter a line : "; cin.getline(line, 100); file << line << endl; // Append the line to the file cout << "Line written into the file" << endl; } return 0; } Copy to clipb Open the file for reading : #include<iostream> #include<fstream> using namespace std; int main() { char line[100];
  • 4. fstream file; // declare an object of fstream class file.open("file.txt", ios :: out | ios :: app); // open file in append mode if (file.fail()) { // check if file is opened successfully // file opening failed cout << "Error Opening file ... " << endl; } else { // proceed with further operations cout << "Enter a line : "; cin.getline(line, 100); file << line << endl; // Append the line to the file cout << "Line written into the file" << endl; } return 0; } Copy to clipb In the first program, we take a line as input from user and appends that line to the “ file.txt “. In the second program, we read the file character by character using get( ) function. Similarly, we can write a single character to a file using put function. Writing class objects to a file There are member functions read( ) and write( ) in the fstream class which allows reading and writing of class objects. These functions can also be used to write array elements into the file. See the program below : #include<iostream> #include<fstream> using namespace std; // define a class to store student data class student { int roll; char name[30]; float marks; public: student() { } void getData(); // get student data from user void displayData(); // display data };
  • 5. void student :: getData() { cout << "nEnter Roll No. : "; cin >> roll; cin.ignore(); // ignore the newline char inserted when you press enter cout << "Enter Name : "; cin.getline(name, 30); cout << "Enter Marks : "; cin >> marks; } void student :: displayData() { cout << "nRoll No. : " << roll << endl; cout << "Name : " << name << endl; cout << "Marks : " << marks << endl; } int main() { student s[3]; // array of 3 student objects fstream file; int i; file.open("objects.txt", ios :: out); // open file for writing cout << "nWriting Student information to the file :- " << endl; for (i = 0; i < 3; i++) { s[i].getData(); // write the object to a file file.write((char *)&s[i], sizeof(s[i])); } file.close(); // close the file file.open("objects.txt", ios :: in); // open file for reading cout << "nReading Student information to the file :- " << endl; for (i = 0; i < 3; i++) { // read an object from a file file.read((char *)&s[i], sizeof(s[i])); s[i].displayData(); } file.close(); // close the file return 0;
  • 6. } Whenever we are taking input from console, we press “enter” key. This leads to a newline character being insert ed in the input buffer. cin ignores this character to take further inputs but cin.getline( ) doesn’t ignore it. Thus, w e need to use the function cin.ignore( ) otherwise, we won’t be able to take further inputs. JazakAllah