FILE HANDLING IN C++
Used to store data in
file, normally when we use variable, will hold the value till run time of
program.
Header File : fstream.h : -
Data type :
1. Ofstream : for
write data,
2. ifstream : for
read and write both,
3. fstream : for read
and write,
Function : - open() , close(),
get() :- to read from file, character by character.
Put() : to write in
file charater by character ,
Read() , write()
Write program : -
#include<fstream.h>
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
ofstream file;
file.open(“test2.txt”);
file<<”onlinestudy.xyz”;
file.close();
cout<<”its done”;
getch();
}
Read program:-
#include<fstream.h>
#include<iosream.h>
#incude<conio.h>
void main()
{
clrscr();
char ch;
ifstream file;
file.open(“test2.txt”);
while(!file.eof())
{
file.get(ch);
cout<<ch;
}
file.close();
cout<<”its done”;
getch();
}
//Count no. of character in file
Void main()
{
clrscr();
ifstream file;
char ch;
int i=0;
file.open(“text2.txt”);
while(!file.eof())
{
file.get(ch);
cout<<ch;
i++;
}
file.close();
cout<<i<<”its
done”;
getch();
}
//count no. of words. (by space count)
void main();
{
clrscr();
ifstream file;
char ch;
int i=0;
file.open(“test3.txt”);
while(!file.eof())
{
file.get(ch);
if(ch==’ ’)
{
i++;
}
}
file.close();
cout<<”its done no. of words is
::”<<++i;
getch();
}
void main()
{
clrscr();
char ch[100];
int
c=0;
ifsream file;
file.open[“text2.txt”];
while(!file.eof())
{
file>>ch;
c++;
}
file.close();
cout<<”is done no. of words is
::”;
getch();
}
// Count no of lines in the file
void main()
{
clrscr();
char ch();
int c=0;
ifstream file;
file.open(“test3.txt”);
while(!file.eof())
{
file.getline(ch,100);
c++;
}
file.close();
cout<<”its done no. of line
:”<<c;
getch();
}
File delete :
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main();
{
clrscr();
char nm[20];
cout<<”enter name of file
delete”;
cin>>nm;
int status=remove(nm);
if(status==0)
{
cout<<”its
done”
}
else
{
cout<<”please check”;
}
getch();
}