In&out_to file
In&out_to file
In&out_to file
C++ provides the following classes to perform output and input of characters to/from files:
Open afile
In order to open a file with a stream object we use its member function open():
Open(filename,mode);
Where filename is a null-terminated character sequence of type const char representing the name of the file to be
opened ,and mode is an following flags:
Closing a file:
infile.close();
outfile.close();
We will no create a simple program for writing of data to file.the program will read number
from the user(keyboard)and store them in a file named file.txt
FACULTY OF ELECTRONICS TECHNOLOGY
Subject: CP II Semester 4th
Input &output with files in C++
#include<iostream>
#include<fstream>
using namespace std;
main()
{
int x;
ofstream outfile(“fileone.txt”);
cout<<endl<<”Enter X :”;
cin>>x;
while(x!=0)
{
outfile<<x<<endl;
cout<<endl<<”Enter X , for Exit enter 0”;
cin>>x;
}
outfile.close();
system(“pause”);
return 0;
}
Example: this program to write in file the iproddid and price untile iproddid=0
#include<iostream>
#include<fstream>
using namespace std;
FACULTY OF ELECTRONICS TECHNOLOGY
Subject: CP II Semester 4th
Input &output with files in C++
main()
{
int iprodid=1;
double dprice;
ofstream outfile(“d:\prodfile.txt”);
while(iprodid!=0)
{
cout<<endl<<”Enter product id:”;
cin>>iprodid;
cout<<” and price :”;
cin>>dprice;
if(iprodid>0)
outfile<<iprodid<<endl<<dprice<<endl;
}
outfile<<iprodid<<endl<<dprice<<endl;
}
outfile.close();
system(“pause”);
return 0;
}
Example : here complete program to read data from th file prodfile.txt and prints the information on the screen.
#include<iostream>
#include<fstream>
using namespace std;
main()
{
char[30];
ifstream infile(“names.txt”);
while(infile.getline(c,29))
cout<<c<<endl;
infile.close();
system(“pause”);
return 0;
}