FILE HANDLING
· All programs we looked earlier
1. Input data from the keyboard
2. output data to the screen
· Output would be lost as soon as we exist from the program
How do we store data permantely?
· We can use secondary storage devices.
· Data is packaged up on the storage device as data structures called files.
Stream Usage
· we have used streams already
3. cin>> --> input from stream object connected to keyboard.
4. cout<< --> Output to stream object conneted to screen.
5. Can define other streams
· To or from files
· Used similarley as cin , cout
File Input and Output Stream
File Input Stream
reads data from disk file to the program.
File Output Stream
Writes data to the disk file from the program
I/O system of C++ contains
6. ifstream : provides input operations on files
7. ofstream: provides output operation on files
8. fstream: supports for simultaneous input and output operations files.
General File I/O steps
9. Declare a file name variables
10. associate the file name variable with the disk file name
11. open the file
12. use the file
13. close the files
File Stream will be in Memory
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)
2.Append mode( It read & Write data into a file )
3. Read mode ( Read data from the file only)
Program-1 : Write the program for Write mode
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
clrscr();
int pid;
char pname[20];
float rate;
cout<<"\n Enter PID and product name and Rate:";
cin>>pid>>pname>>rate;
ofstream ob;
ob.open("inventory.txt");
ob<<pid;
ob<<"\t";
ob<<pname;
ob<<"\t";
ob<<rate;
ob<<"\n";
cout<<"\n Data stored in to file successfully";
getch();
}
To Check the file location
press window+E ( PC) -->local disk(C)--> TurboC3--> Bin--> inventory.txt
Program-2 : write a program for Append mode
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
clrscr();
int pid;
char pname[20];
float rate;
cout<<"\n Enter PID and product name and 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";
cout<<"\n Data stored in to file successfully";
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;
cout<<"\n Enter file name to open";
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();