Data File Handling
Data File Handling
Data File Handling
Introduction
We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
error checking and handling EOF
• A file can be opened in two ways:
1. Using constructor function
2. Using member function
Opening file using constructor
• ifstream infile(“data”);
outfile<<“total”;
outfile.close();
infile>> string;
Opening files using member function
open()
• This function is used to open multiple files that uses
same stream object.
• Syntax:-
file_stream class stream_object;
stream_object.open(“filename”);
Example
ofstream outfile;
outfile.open(“Data”);
…………………..
…………………..
outfile.close();
outfile.open(“Data2”);
…………………….
…………………..
outfile.close();
Open(): File Modes
stream-object.open(“filename”,mode);
• EOF()
Void main()
{
Ifstream infile;
Infile.open(“text”);
While(!infile.eof())
{
------
-----
}}
• FAIL()
Main()
{
Ifstream infile;
Infile.open(“text”);
While(!infile.fail())
{
Cout<<“cudn’t open a file”;
}}
Reading and Writing in Files
1) ofstream fileout;
fileout.open(“hello”,ios::app);
2)fileout.open(“hello”, ios::in | ios::out);