Você está na página 1de 25

File

A file is a collection of related data stored in


a particular area on the disk . The data is
stored in disk using the concept of file .

File Handling in C++


Why File
Permanent storage of data : - (all the message or
value printed with help of any output statements
like printf , putchar are never available for future
use ) .

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.
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.

The transfer of input – data or output –


data from one computer to another can be
easily done by using files.
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.

Fsream :- 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
Function Operation
open() To create a file
To close an existing
close()
file
Read a single
get()
character from a file
write a single
put()
character in file.
read() Read data from file
write() Write data into file.
Opening file using open()

The function open() can be used to open


multiple files that use the same stream object.

file-stream-class stream-object;
stream-object . open (“filename”);
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();
……………………………..
Example: Word File
Mode of file opening
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
Set the initial position at the end of the file.
ios::ate
If this flag is not set, the initial position is the beginning of the file.

All output operations are performed at the end of the file,


ios::app
appending the content to the current content of the file.
If the file is opened for output operations and it already existed, its
ios::trunc
previous content is deleted and replaced by the new one.

Both ios :: app and ios :: ate take us to the end of the file
when it is opened. The difference between the two
parameters is that the ios :: app allows us to add data to
the end of file only, while ios :: ate mode permits us to add
data or to modify the existing data any where in the file.
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);
File pointer
Each file have two associated pointers known as
the file pointers. One of them is called the input
pointer (or get pointer) and the other is called the
output pointer (or put pointer). The input pointer
is used for reading the contents of a given file
location and the output pointer is used for writing
to a given file location.
Function for manipulation
of file pointer
When we want to move file pointer to desired
position then use these function for manage the
file pointers.

Seekg () = moves get pointer (input) to a


specified location
Seekp () = moves put pointer (output) to a
specified location
tellg () = gives the current position of the get pointer
tellp () = gives the current position of the put pointer
fout . seekg(0, ios :: beg) -- go to start
fout . seekg(0, ios :: cur) -- stay at current position
fout . seekg(0, ios :: end) -- go to the end of file
fout . seekg(m, ios :: beg) -- move to m+1 byte in the file
fout . seekg(m, ios :: cur) -- go forward by m bytes
from
the current position
fout . seekg(-m, ios :: cur) -- go backward by m bytes
from the current position
fout . seekg(-m, ios :: end) -- go backward by m bytes
from the end
put() and get() function
The function put() write a single character to the
associated stream. Similarly, the function get()
reads a single character from the associated
stream.

 file.get(ch);
 file.put(ch);
read() and write() function
write ( memory_block, size );
read ( memory_block, size );

Where memory_block is of type char* (pointer to char), and represents the


address of an array of bytes where the read data elements are stored or from where
the data elements to be written are taken.

The size parameter is an integer value that specifies the number of


characters to be read or written from/to the memory block.

file . read ((char *)&V , sizeof (V));


file . Write ((char *)&V , sizeof (V));

These function take two arguments. The first is the address of the
variable V , and the second is the length of that variable in bytes .
The address of variable must be cast to type char * (i.e pointer to
character type) .
Error Handling
 Sometimes during file operations, errors may also creep in. For
example, a file being opened for reading might not exist. Or a file
name used for a new file may already exist. Or an attempt could be
made to read past the end-of-file. Or such as invalid operation may
be performed. There might not be enough space in the disk for
storing data.

 To check for such errors and to ensure smooth processing, C++ file
streams inherit 'stream-state' members from the ios class that store
the information on the status of a file that is being currently used.
The current state of the I/O system is held in an integer, in which
the following flags are encoded :
Stream Errors

C++ Error Handling Functions


ifstream fin;
fin.open("master", ios::in);
while(!fin.fail())
{
: // process the file
}
if(fin.eof())
{
: // terminate the program
}
else if(fin.bad())
{
: // report fatal error
}
else
{ fin.clear(); // clear error-state flags
:
}
Example Program
Count number of words in a text file
#include<fstream>
#include<iostream>
#include<string>
using namespace std;

int main()
{
ifstream inFile; //Declares a file stream
object
string word;
int count = 0;

inFile.open(“fileName”); cout << "Number of words in file is " << count;


inFile.close();
while(!inFile.eof())
{ return 0;
inFile >> word; }
count++;
}
Program to write in a text file

#include<fstream.h>
int main()
{
ofstream fout;
fout.open("out.txt");
char str[300]=“Welcome to the Programming World";
fout<<str;
fout.close();
return 0;
}
Program to read from text file and display it
#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
Count number characters in a text file
#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
clrscr();
char ch;
int count=0;
while(!fin.eof())
{
fin.get(ch);
count++;
}
cout<<"Number of characters in file is "<<count;
fin.close();
getch();
return 0;
}
Program to count number of lines

#include<fstream.h>
#include<conio.h>
int main()
{
ifstream fin;
fin.open("out.txt");
char str[80];
int count=0;
while(!fin.eof())
{
fin.getline(str,80);
count++;
}
cout<<"Number of lines in file is "<<count;
fin.close();
getch();
return 0;
}
Program to copy contents of file to another file.

#include<fstream.h>
int main()
{
ifstream fin;
fin.open("out.txt");
ofstream fout;
fout.open("sample.txt");
char ch;
while(!fin.eof())
{
fin.get(ch);
fout<<ch;
}
fin.close();
return 0;
}

Você também pode gostar