assignment-2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

SYED MOIZ ALI CMS:32798

ASSIGNMENT # 2
File handling:
What is file handling?

File Handling in C++ is used to store, write or read the data permanently in computer’s hard
disk. By using file handling we can store data is secondary data.

Usage of file handling:

We use file handling for.

I. Permanently store data.


II. For transferring the data. By using file handling we can easily transfer desired data from one
computer to another computer.

For file handling we need another C++ library called fstream, which defines another three new data
type.

i. ifstream: It is used to read the data from the file.


ii. fstream: it is used to write or read the data from or into the file.
iii. ofstream: it is used to create and write data on this file.

Steps:

The steps involved are:

1. Name a file.
2. Open a file.
3. Read / write data on file.
4. Close a file.

Function used:

i. open(): To create a file.


ii. close(): To close a file.
iii. get(): Read a single character from file.
iv. put(): Write a single character from a file.
v. write(): Write a data from a file.
vi. read(): Read a data from a file.

1
SYED MOIZ ALI CMS:32798

Code:

For ofstream code:


The ofstream used to create a file and enables user to write data on that file.

For example:

Ofstream writer(“Moiz.txt”);

This create a “txt” file in memory in project folder of visual studio.

Main code:
#include<iostream>
#include<conio.h>
using namespace std;
#include<fstream>
void main()
{
ofstream writer("Moiz.txt");
writer<<"this is my fir";
getch();
}

After execution:

After execution a “txt” file is created named as Moiz.

2
SYED MOIZ ALI CMS:32798

As By using ofstream we can also write data into file as shown.

For ifstream code:


The ifstream code is used to read the data from the file.

For example:

ifstream reader("Moiz.txt");

This read a “txt” file in memory in project folder of visual studio.

Main code:
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
void main()
{
int c;
ifstream reader("Moiz.txt");
int a, b;
reader>>a>>b;
cout<<a+b;
getch();

3
SYED MOIZ ALI CMS:32798
}

AS shown two variables are declared in txt file.


When the program executes the program adds these two variables and shows the answer as
sum of those variables.

You might also like