C++ Files and Streams
Objectives
➢C++ I/O streams.
➢Reading and writing sequential files.
➢Member Functions of Stream Classes
File
“A file is a collection of information, usually
stored on a computer’s disk. Information can be
saved to files and then later reused.”
File Names
All files are assigned a name that is used for
identification purposes by the operating system
and the user.
Why File?
(all the message or value printed with help of any output
statements like cout , put are never available for future use )
1. If there is a large amount of data generated as output by a
program, storing that output in file will help in easy handling
/analysis of the output as user can see the whole output at any
time even after complete execution of the program.
2. If we need lot of data to be inputted, user cannot keep on
typing that again and again for repeated execution of program. In
that case, all input data can be once written in a file and then that
file can be easily used as the input file.
3. The transfer of input – data or output – data from one
computer to another can be easily done by using files.
The Process of Using a File
Using a file in a program is a simple three-step
process
1. The file must be opened. If the file does not yet exists,
opening it means creating it.
2. Information is then saved to the file, read from the file,
or both.
3. When the program is finished using the file, the file
must be closed.
Stream Classes
Ifstream: provides input operations.
Contains open() with default input mode.
Inherits the functions
get(), getline(), read(), seekg() and tellg() function from istream.
Ofstream: provides output operations.
Contains open() with default output mode.
Inherits
put(), seekp(), teelp() and write() function from ostream.
Fstream : provides support for simultaneous input and output
operations.
Contains open() with default input mode.
Inherits all the function from isteram and ostream classes through
iostream
▪ C++ views each files as a sequence of bytes
▪ Each file ends with an end-of-file marker.
▪ When a file is opened, an object is created and a
stream is associated with the object.
▪ To perform file processing in C++,
the header files <iostream> and <fstream>
must be included.
▪ <fstream.> includes <ifstream> and <ofstream>
Reading/writing text streams
All programs we’ve written so far have read
input from standard input, and written output
to standard output.
cin, cout, and cerr are C++ streams.
We will now extend this concept to disk files.
Reading strings from streams (code fragment):
#include <iostream>
...
ifstream input_data;
input_data.open(“myfile”);
string s;
input_data >> s; // read word
getline(input_data,s);
...
Reading characters from streams (code fragment):
#include <iostream>
...
ifstream input_data;
input_data.open(“myfile”);
char ch;
input_data.get(ch); // get one character
...
C++ streams
//Add additional header files
you use
#include <fstream>
using namespace std;
int main ()
{ /* Declare file stream
variables such as the following
*/
ifstream fsIn;//input
ofstream fsOut; // output
fstream both; //input & output
//Open the files
fsIn.open("prog1.txt"); //open
the input file
fsOut.open("prog2.txt"); //open
the output file
//Code for data manipulation
.
//Close files
fsIn.close();
fsOut.close();
return 0; }
Object and Member Functions
input_stream.open("numbers.txt“)
File Open Modes
1. ios:: app - (append) write all output to the end of file
2. ios:: ate - data can be written anywhere in the file
3. ios:: binary - read/write data in binary format
4. ios:: in - (input) open a file for input
5. ios::out - (output) open a file for output
6. ios: trunc -(truncate) discard the files’ contents if it exists
7. ios:nocreate - if the file does NOT exists, the open operation fails.
8. ios:noreplace - if the file exists, the open operation fails
Open and Close a file
eg:-
ofstream outfile; // create stream
outfile . open (“DATA1”); // connect stream to DATA1
……………………………..
……………………………..
outfile . Close(); //disconnect stream from DATA1
outfile . Open(“DATA2”); //connect stream to DATA2
……………………………..
……………………………..
outfile . close();
The mode can combine two or more parameters
using the bitwise OR operator (symbol |)
eg :-
fstream file;
file . Open(“ data . txt”, ios :: out | ios :: in);
Opening a File
For opening a file, we must first create a file
stream and then link it to the filename.
A file can be opened in two ways:
1. Using the constructor function of the class.
2. Using the member function open() of the
class.
Opening File using Constructor
A constructor is used to initialize an object while it is being
created.
In the same manner, a file name is used to initialize the file stream
object.
This involves the following steps:
1. Create a file stream object to manage the stream using the
appropriate class, i.e. the class ofstream is used to create the
output stream and the class ifstream is used to create the input
stream.
2. Initialized the file object with the desired filename.
e.g:
Ofstream outfile(“results”); //output only
This statement opens the file results and attaches it
to the output stream outfile.
Ifstream infile(“data”); //input only
Similarly, above statement declares infile as an
ifstream object and attaches it to the file data for
reading (input)
File I/O Example: Open the file with
validation
First Method (use the constructor) Second Method ( use Open function)
#include <fstream> #include <fstream>
#include <iotream>
#include <iotream>
using namespace std;
using namespace std;
int main()
int main() {
{ //declare output file variable
//declare and automatically ofstream outFile;
open the file // open an exist file fout.txt
ofstream outFile(“fout.txt"); outFile.open(“fout.txt”);
// Open validation // Open validation
if(! outFile) { if(! outFile.is_open() ) {
Cout << “Cannot open file.\n ”; Cout << “Cannot open file.\n ”;
return 1; return 1;
} }
return 0;
return 0;
}
}
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream outfile(“OOP.txt");
cout<<"enter Name";
string name;
cin>>name;
outfile<<name;
outfile.close();
ifstream infile(“OOP.txt");
infile>>name;
cout<<"\nname= "<<name<<endl;
return 0;
}
File I/O Example: Writing
First Method (use the constructor) Second Method ( use Open function)
#include <fstream> #include <fstream>
using namespace std; using namespace std;
int main() int main()
{/* declare and automatically {// declare output file
open the file*/ variable
ofstream outFile("fout.txt"); ofstream outFile;
// open an exist file fout.txt
//behave just like cout, put outFile.open("fout.txt”);
the word into the file
outFile << "Hello World!"; //behave just like cout, put
the word into the file
outFile.close(); outFile << "Hello World!";
return 0; outFile.close();
}
return 0;
}
Example writing to file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile;
// open an exist file fout.txt
outFile.open("number.txt",ios::app);
if (!outFile.is_open())
{ cout << " problem with opening the file ";}
else
{outFile <<200 <<endl ;
cout << "done writing" <<endl;}
outFile.close();
return 0;
}
Example Reading from file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{//Declare and open a text file
ifstream INFile("number.txt");
string line;
int total=0;
while(! INFile.eof())
{
getline(INFile, line);
//converting line string to int
stringstream(line) >> total;
cout << line <<endl;
cout <<total +1<<endl;}
INFile.close(); // close the file
return 0; }
Note
When a file is opened for writing only,
• a new file is created if there is no file of that
name.
• if a file by that name exists already , then its
contents are deleted and the file is presented as a
clean file .
How to open an existing file for updating it without
loosing its original contents?
Opening Files Using open()
1. The function open() can be used to open
multiple files that use the same stream object.
2. If we want to open file sequentially, we may
create a single stream object and use it to
open each file in turn.
file-stream-class stream-object;
stream-object.open(“filename”);
#include<iostream> Working with Multiple Files
#include<fstream>
#include<string>
using namespace std;
int main() string line;
{ ifstream infile;
ofstream outfile; infile.open("First.txt");
while(infile)
outfile.open("Next.txt"); {
getline(infile,line);
outfile<<"Tashkent "<<endl; cout<<line<<endl;
outfile<<"Samarkhand"<<endl; }
outfile<<"Bukhara"<<endl; infile.close();
outfile.close();
infile.open("next.txt");
outfile.open("First.txt"); while(infile)
{
outfile<<"Tashkent- Frist"<<endl; getline(infile,line);
outfile<<"Samarkhand- first"<<endl; cout<<line<<endl;
outfile<<"Bukhara- first"<<endl; }
infile.close();
outfile.close(); return 0;
}
Detecting END-OF-FILE
• Detection of end-of-file condition necessary for
preventing any further attempt to read data from the file.
while(fin)
• An ifstream object, such as fin, returns a value of 0 if
any error occurs in the file operation including the end-
of-file condition.
If(fin1.eof()!=0){exit(1);}
eof is a member function of IOS class.
It returns a non-zero value if the end-of-file(EOF)
condition is encountered, and a zero, otherwise.
Member Functions of Stream Classes
➢good() returns true if the stream is in a valid state
for input/output operations.
➢bad() returns true if a non-recoverable error has
occurred on the stream.
➢eof() returns true if the end-of-file has been
reached on the input stream.
➢fail() returns true if a recoverable error has
occurred on the stream.
Reading from Two Files Simultaneously
Program 2
int main() ifstream infile;
{ infile.open("odd.txt");
ofstream outfile; cout<<"\n ODD NUMBERS ARE :- \n";
outfile.open("odd.txt"); while (infile.eof()==0)
for(int i=0;i<10;i++) {
{ infile >> num;
if(i%2!=0) cout<<num<<endl;
outfile<<i<<endl; }
} infile.close();
outfile.close(); infile.open("even.txt");
cout<<"\n EVEN NUMBERS ARE :- \n";
outfile.open("even.txt"); while((infile.eof())==0)
for(int i=0;i<10;i++) {
{ infile>>num;
if(i%2==0) cout<<num<<endl;
outfile<<i<<endl; }
} infile.close();
outfile.close(); return 0;
}
int num;