T1_U5_File Handling
T1_U5_File Handling
Stream Usage
· To or from files
10. associate the file name variable with the disk file name
C++ Views file as sequence of bytes Ends with end of file marker
File Modes
1. Write mode ( It only write the data into file , it override the previousely stored data into as file)
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
clrscr();
int pid;
char pname[20];
float rate;
cin>>pid>>pname>>rate;
ofstream ob;
ob.open("inventory.txt");
ob<<pid;
ob<<"\t";
ob<<pname;
ob<<"\t";
ob<<rate;
ob<<"\n";
getch();
}
To Check the file location
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
clrscr();
int pid;
char pname[20];
float rate;
cin>>pid>>pname>>rate;
ofstream ob;
ob.open("inventory.txt",ios::app);
ob<<pid;
ob<<"\t";
ob<<pname;
ob<<"\t";
ob<<rate;
ob<<"\n";
getch();
}
Program-3 : write a program for read mode
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<string.h>
void main()
{
clrscr();
fstream fp;
char fname[30],str[100];
int i=0;
gets(fname);
fp.open(fname,fstream::in);
fp.getline(str,1000);
while(strlen(str>0))
cout<<str<<"\n";
fp.getline(str,1000);
fp.close();
getch();