0% found this document useful (0 votes)
10 views17 pages

Files and Streams

The document provides a comprehensive overview of file handling in C++ using the fstream, ifstream, and ofstream classes. It includes various code examples demonstrating how to create, read, and write to files, as well as how to manage data using classes and structures. Additionally, it covers functions like tellg(), tellp(), seekg(), and seekp() for file position management.

Uploaded by

yogitas804
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views17 pages

Files and Streams

The document provides a comprehensive overview of file handling in C++ using the fstream, ifstream, and ofstream classes. It includes various code examples demonstrating how to create, read, and write to files, as well as how to manage data using classes and structures. Additionally, it covers functions like tellg(), tellp(), seekg(), and seekp() for file position management.

Uploaded by

yogitas804
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Files and Streams

In C++ programming we are using the iostream standard library, it


provides cin and cout methods for reading from input and writing to
output respectively.
To read and write from a file we are using the standard C++ library
called fstream. Let us see the data types define in fstream library is:

Data Description
Type

fstream It is used to create files, write information to files, and read


information from files.

ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.

Creating a file using file stream


//C++ program to create a file.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}

cout<<"File created successfully.";

//closing the file


file.close();
return 0;
}

Program to read text character by


character in C++
#include<iostream>
#include<fstream>
using namespace std;

int main()
{
char ch;
const char *fileName="test.txt";

//declare object
ifstream file;

//open file
file.open(fileName,ios::in);
if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return -1; //return from main
}

//read and print file content


while (!file.eof())
{
file >> noskipws >> ch; //reading from file
cout << ch; //printing
}
//close the file
file.close();

return 0;
}

Write and read text in/from file


//C++ program to write and read text in/from file.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}

cout<<"File created successfully."<<endl;


//write text into file
file<<"ABCD.";
//closing the file
file.close();

//again open file in read mode


file.open("sample.txt",ios::in);

if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}

//read untill end of file is not found.


char ch; //to read single character
cout<<"File content: ";

while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}

file.close(); //close file

return 0;
}

Write and read variable's values in the file


//C++ program to write and read values using variables in/from
file.
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char name[30];
int age;
fstream file;

file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;

//read values from kb


cout<<"Enter your name: ";
cin.getline(name,30);
cout<<"Enter age: ";
cin>>age;
//write into file
file<<name<<" "<<age<<endl;

file.close();
cout<<"\nFile saved and closed succesfully."<<endl;

//re open file in input mode and read data


//open file
file.open("aaa.txt",ios::in);
if(!file){
cout<<"Error in opening file..";
return 0;
}
file>>name;
file>>age;

cout<<"Name: "<<name<<",Age:"<<age<<endl;
return 0;
}

Write and read object values in the file


using read and write function
//C++ program to write and read object using read and write
function.
#include <iostream>
#include <fstream>
using namespace std;

//class student to read and write student details


class student
{
private:
char name[30];
int age;
public:
void getData(void)
{ cout<<"Enter name:"; cin.getline(name,30);
cout<<"Enter age:"; cin>>age;
}

void showData(void)
{
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};

int main()
{
student s;

ofstream file;

//open file in write mode


file.open("aaa.txt",ios::out);
if(!file)
{
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;
//write into file
s.getData(); //read from user
file.write((char*)&s,sizeof(s)); //write into file

file.close(); //close the file


cout<<"\nFile saved and closed succesfully."<<endl;

//re open file in input mode and read data


//open file1
ifstream file1;
//again open file in read mode
file1.open("aaa.txt",ios::in);
if(!file1){
cout<<"Error in opening file..";
return 0;
}
//read data from file
file1.read((char*)&s,sizeof(s));

//display data on monitor


s.showData();
//close the file
file1.close();

return 0;
}

tellg() and tellp() example in c++


//C++ program to demonstrate example of tellg() and tellp()
function.

#include <iostream>
#include <fstream>

using namespace std;


int main()
{
fstream file;
//open file sample.txt in and Write mode
file.open("sample.txt",ios::out);
if(!file)
{
cout<<"Error in creating file!!!";
return 0;
}
//write A to Z
file<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//print the position
cout<<"Current position is: "<<file.tellp()<<endl;
file.close();

//again open file in read mode


file.open("sample.txt",ios::in);
if(!file)
{
cout<<"Error in opening file!!!";
return 0;
}
cout<<"After opening file position is: "<<file.tellg()<<endl;

//read characters untill end of file is not found


char ch;
while(!file.eof())
{
cout<<"At position : "<<file.tellg(); //current
position
file>>ch; //read character from file
cout<<" Character \""<<ch<<"\""<<endl;
}
//close the file
file.close();
return 0;
}

C++ program to demonstrate the example


of tellg(), seekg() and seekp()
In the below program, we are using a file 'my.txt', the file contains
the following text,
File: my.txt
IncludeHelp is specially designed to provide help to students,
working professionals and job seekers
Program:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
fstream F;
// opening a file in input and output mode
F.open("my.txt", ios::in | ios::out);

// getting current location


cout << F.tellg() << endl;

// seeing 8 bytes/characters
F.seekg(8, ios::beg);
// now, getting the current location
cout << F.tellg() << endl;
// extracting one character from current location
char c = F.get();
// printing the character
cout << c << endl;
// after getting the character,
// getting current location
cout << F.tellg() << endl;
// now, seeking 10 more bytes/characters
F.seekg(10, ios::cur);
// now, getting current location
cout << F.tellg() << endl;
// again, extracing the one character from current location
c = F.get();
// printing the character
cout << c << endl;

// after getting the character,


// getting current location
cout << F.tellg() << endl;
// again, seeking 7 bytes/characters from beginning
F.seekp(7, ios::beg);
// writting a character 'Z' at current location
F.put('Z');
// now, seeking back 7 bytes/characters from the end
F.seekg(-7, ios::end);
// now, printing the current location
cout << "End:" << F.tellg() << endl;
// extracting one character from current location
c = F.get();
// printing the character
cout << c << endl;

// closing the file


F.close();
return 0;
}
C++ Code Snippet - Employee
Management Program using C++ File
Handling/Stream Program
#include<iostream>
#include<fstream>
#include<stdio.h>

using namespace std;

//Employee class Declaration


class Employee{
private:
int code;
char name[20];
float salary;
public:
void read();
void display();
//will return employee code
int getEmpCode() { return code;}
//will return employee salary
int getSalary() { return salary;}
//will update employee salary
void updateSalary(float s) { salary=s;}
};

//Read employee record


void Employee::read(){
cout<<"Enter employee code: ";
cin>>code;
cout<<"Enter name: ";
cin.ignore(1);
cin.getline(name,20);
cout<<"Enter salary: ";
cin>>salary;
}

//Display employee record


void Employee::display()
{
cout<<code<<" "<<name<<"\t"<<salary<<endl;
}

//global declaration
fstream file;

//Will delete file when program is being executed


//because we are create file in append mode
void deleteExistingFile(){
remove("EMPLOYEE.DAT");
}

//function to append record into file


void appendToFille(){
Employee x;

//Read employee record from user


x.read();

file.open("EMPLOYEE.DAT",ios::binary|ios::app);
if(!file){
cout<<"ERROR IN CREATING FILE\n";
return;
}
//write into file
file.write((char*)&x,sizeof(x));
file.close();
cout<<"Record added sucessfully.\n";
}

void displayAll(){
Employee x;

file.open("EMPLOYEE.DAT",ios::binary|ios::in);
if(!file){
cout<<"ERROR IN OPENING FILE \n";
return;
}
while(file){
if(file.read((char*)&x,sizeof(x)))
if(x.getSalary()>=10000 && x.getSalary()<=20000)
x.display();
}
file.close();
}

void searchForRecord(){
//read employee id
Employee x;
int c;
int isFound=0;

cout<<"Enter employee code: ";


cin>>c;

file.open("EMPLOYEE.DAT",ios::binary|ios::in);
if(!file){
cout<<"ERROR IN OPENING FILE \n";
return;
}
while(file){
if(file.read((char*)&x,sizeof(x))){
if(x.getEmpCode()==c){
cout<<"RECORD FOUND\n";
x.display();
isFound=1;
break;
}
}
}
if(isFound==0){
cout<<"Record not found!!!\n";
}
file.close();
}

//Function to increase salary


void increaseSalary(){
//read employee id
Employee x;
int c;
int isFound=0;
float sal;

cout<<"enter employee code \n";


cin>>c;

file.open("EMPLOYEE.DAT",ios::binary|ios::in);
if(!file){
cout<<"ERROR IN OPENING FILE \n";
return;
}
while(file){
if(file.read((char*)&x,sizeof(x))){
if(x.getEmpCode()==c){
cout<<"Salary hike? ";
cin>>sal;
x.updateSalary(x.getSalary()+sal);
isFound=1;
break;
}
}
}
if(isFound==0){
cout<<"Record not found!!!\n";
}
file.close();
cout<<"Salary updated successfully."<<endl;
}

//Insert record by assuming that records are in


//ascending order
void insertRecord(){
//read employee record
Employee x;
Employee newEmp;

//Read record to insert


newEmp.read();

fstream fin;
//read file in input mode
file.open("EMPLOYEE.DAT",ios::binary|ios::in);
//open file in write mode
fin.open("TEMP.DAT",ios::binary|ios::out);

if(!file){
cout<<"Error in opening EMPLOYEE.DAT file!!!\n";
return;
}
if(!fin){
cout<<"Error in opening TEMP.DAT file!!!\n";
return;
}
while(file){
if(file.read((char*)&x,sizeof(x))){
if(x.getEmpCode()>newEmp.getEmpCode()){
fin.write((char*)&newEmp, sizeof(newEmp));
}
//no need to use else
fin.write((char*)&x, sizeof(x));
}
}

fin.close();
file.close();

rename("TEMP.DAT","EMPLOYEE.DAT");
remove("TEMP.DAT");
cout<<"Record inserted successfully."<<endl;
}

int main()
{
char ch;

//if required then only remove the file


deleteExistingFile();

do{
int n;
cout<<"ENTER CHOICE\n"<<"1.ADD AN EMPLOYEE\n"<<"2.DISPLAY\
n"<<"3.SEARCH\n"<<"4.INCREASE SALARY\n"<<"5.INSERT RECORD\n";
cout<<"Make a choice: ";
cin>>n;

switch(n){
case 1:
appendToFille();
break;
case 2 :
displayAll();
break;
case 3:
searchForRecord();
break;
case 4:
increaseSalary();
break;
case 5:
insertRecord();
break;

default :
cout<<"Invalid Choice\n";
}

cout<<"Do you want to continue ? : ";


cin>>ch;

}while(ch=='Y'||ch=='y');

return 0;
}

C++ Code Snippet - Read Characters from


One file and Write in Other in Toggle Case
#include<iostream>
#include<fstream>
#include<ctype.h>

using namespace std;

int main()
{
ifstream fin;
ofstream fout;

//creating a file and writing smething


fout.open("alex.txt",ios::out);
if(!fout){
cout<<"Error\n";
return -1;
}
//write text into file
fout<<"Hello World.";
fout.close();
//////////////////////////////////////

fin.open("alex.txt",ios::in);
fout.open("new.txt",ios::out);
if(!fin||!fout){
cout<<"ERROR\n";
return -1;
}

char ch;
while(fin)
{
if(fin.get(ch))
{
if(isupper(ch))
ch+=32;
else if(islower(ch))
ch-=32;
}
fout.put(ch);
}

fin.close();
fout.close();
//print the content of net.txt
fin.open("new.txt",ios::in);
if(!fin){
cout<<"Error";
return -1;
}
cout<<"Content of new.txt file :\n";
while(fin){
if(fin.get(ch))
cout<<ch;
}
cout<<endl;
fin.close();
///////////////////////////////
return 0;
}

You might also like