0% found this document useful (0 votes)
19 views56 pages

File Handling

Uploaded by

d4n67jnkr5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views56 pages

File Handling

Uploaded by

d4n67jnkr5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

File Handling

Introduction
∙ Many real-life problems handle large volumes of
data.
∙ The data is stored in the devices using the concept of
files.
∙A file is a collection of related data
stored in a particular area on the disk.
∙ Programs are designed to perform read and
write operations on these files.
Console-Program-File interaction
Program File Communication
∙ In C++ file streams are used as an interface
between the program and the files.
∙ The stream that supplies data to the program is
known as input stream and the one that receives
data from the program is known as output stream.

∙ Input stream => reads data


∙ Output stream => writes data
File input and Output Streams
Classes for File Stream Operations

ios

iostream
file
istream streambuf ostream

iostream

ifstream fstream ofstream filebuf


fstream
file

fstream base
Opening and Closing a File
∙ To open a file, a file stream is created and then it
is linked to the filename.

∙ A file can be opened in two ways:


▫Using the constructor function of the class.
▫Using the member function open() of the class.
∙ A file is closed by using the function close().
∙ eg: outfile.close();
Opening File using Constructor
∙ Filename is used to initialize the file stream object.
∙ Create a file stream object to manage the stream.
▫ ofstream is used to create output stream.
▫ ifstream is used to create input stream.
∙ Initialize the file object with the desired filename.
∙ Eg:

ofstream outfile (“results”); // output only


ifstream infile (“data”); // input only
EXAMPLE
EXAMPLES
EXAMPLES
C++ provides us a few file stream classes which allow us perform file
output/write operation by using the put() function. These file stream classes
are:
● ofstream class - This class gives access to the put() function, which is
used to perform the file output operation.
● fstream class - This class also gives access to the put() function to
allow us to perform any file output operation, and it also provides
functions to provide file input operation.

In order to perform a file input/read operation by using the get() function,


C++ provides us a few file stream classes, such as:
● ifstream class - This class gives access to the get() function, which is
used to perform a file input operation.
● fstream class - This class also gives access to the get() function to
perform file input operation, and it also provides functions to perform
file output operation.
TASK : Output ???
Using the get() function to perform the file input operation.
//C++ Reading the content to a file using ifstream class and file mode ios::in

#include<iostream>
#include<ifstream>
using namespace std;
int main()
{
//Creating an input stream to read a file
ifstream ifstream_ob;

//Opening a file named File1.txt to read its content


ifstream_ob.open("example.txt", ios::in);

char ch;
//Reading the file using get() function and displaying its content
while(ifstream_ob)
{
ch = ifstream_ob.get();
cout<<ch;
}
//Closing
ifstream_ob.close();
return 0;
}
//C++ Writing data to a file using put() function and ios::out mode

#include<iostream>
#include<fstream>
#include<cstring>

using namespace std; TASK : Output ???


int main()
{
//Creating an output stream to write data to a file
ofstream ofstream_ob;
//Opens/creates a file named File2.txt
ofstream_ob.open("File2.txt", ios::out);

char arr[100] = "Hello World. We wish you best in everything. Never give up!";

int length = strlen(arr);


char ch;

//Reading the char array i.e. a character at a time and writing it to the file
for(int i=0; i<length; i++)
{
ch = arr[i];
ofstream_ob.put(ch); //Writing a character to file, by using put() function
}
//Closing the output stream
ofstream_ob.close();
return 0;
}
TASK : Output ???
Opening Files Using open()
∙ The function open() can be used to open
multiple files that use the same stream object.

∙ Syntax:
File-stream-class stream-object;
stream-object.open(“filename”);
∙ A stream object can be connected to only one file
at a time.
TASK : FIND OUTPUT
#include<iostream.h> #include<fstream.h>

int main()
{
ofstream fout;
fout.open(“Country”);

fout<<“United state of America”;


fout<<“United Kingdom”;
fout.close();

fout.open(“Capital”);

fout<<“Washington”; fout<<“London”;

fout.close();
TASK : FIND OUTPUT
const int N=80;
char line[N];

ifstream fin;
fin.open(“Country”);

cout<<“Contents of country file” ;


while(fin)
{
fin.getline(line, N);
cout<<line;
}
fin.close();
TASK : FIND OUTPUT

fin.open(“Capital”);

cout<<“Contents of capital file”;

while(fin)
{
fin.getline(line, N);
cout<<line;
}
fin.close();
return 0;
}
NOTE:Opening two files simultaneously

∙ When two or more files are used simultaneously


ie: when we want to merge two files into a single
file.
∙ In such case we create two separate input
streams for handling the two input files and one
output stream for handling the output file.
Opening two files simultaneously

#include <iostream> // Include the necessary header files.


#include <fstream>
#include <cstdlib>

using namespace std; // Declare the standard namespace for easier code readability.

int main() {
const int size = 80; // Define the maximum size for the character array.

char line[size]; // Create a character array to store lines from files.


ifstream fin1, fin2; // Declare input file stream objects for two files.

fin1.open("country"); // Open the file named "country".


fin2.open("capital"); // Open the file named "capital".

if (!fin1.is_open() || !fin2.is_open()) {
cout << "Failed to open one or both of the files." << endl;
return 1;
}

for (int i = 1; i <= 10; i++) {


if (fin1.eof() != 0) {
cout << "\nExit from country file.\n";
exit(1);
}
Detecting End-of File

∙ Detection of the end-of-file condition is necessary


for preventing any further attempt to read data from
the file.
while(fin)
∙ An ifstream object return a value zero if any error
occurs in the file operation including the end-of-file
condition.
if(fin1.eof() != 0 ) { exit(1); }
∙ The eof() of ios class returns a non zero value if the
end-of-file condition is encountered and zero
otherwise.
• What are default arguments?
▫ A default argument is a value provided in
function declaration that is automatically assigned
by the compiler if caller of the function doesn't
provide a value for the argument.
stream_object.open(“filename”,mode)
File Modes
∙ File mode specifies the purpose for which the file is
opened.
∙ File mode parameters:

▫ ios::app //Append to end-of-file


▫ ios::ate //go to end-of-file on opening
▫ ios::binary //Binary file
▫ ios::in //open file for reading only
▫ ios::nocreate //open fails if the file does not exists.

▫ ios::noreplace //open fails if the file already exists.

▫ ios::out //open file for writing only


▫ ios::trunc //delete the contents of file if it exists
File Pointers
∙ Each file has two associated pointers:
get pointer or input pointer: used for reading the contents of the
file.
put pointer or output pointer: used for writing to a given file
location.

∙ Default actions are associated with both the pointers.


▫ When a file is opened in read mode the input pointer is set at the
beginning.

▫ When a file is opened in write mode the existing contents are


deleted and output pointer is set at beginning.
Default Actions
Manipulation of File Pointers
∙ The user can control the movement of the pointers as per
programming need by using the following functions:
seekg() : moves get pointer to a specified location.
seekp(): moves put pointer to a specified location.
tellg() : gives the current position of the get pointer.
tellp() : gives the current position of the put pointer.

1. cout: This is the standard output


stream, which is used for regular
NOTE
program output, such as printing
normal messages and data to the
console.
2. cerr: This is the standard error
stream, which is used for error
messages, warnings, and diagnostic
information. I
#include <iostream>
#include <fstream>

int main() {
// Create an output file stream and open a file for writing
EXAMPLE
std::ofstream outputFile("example.txt");

// Write data to the file


outputFile << "This is a sample text file.\n";
outputFile << "It contains multiple lines of text.\n";
outputFile << "We will use seekg, seekp, tellg, and tellp in this example.\n";
outputFile.close(); // Close the file

// Open the file for reading


std::ifstream inputFile("example.txt");

if (!inputFile) {
std::cerr << "Failed to open the file for reading." << std::endl;
return 1;
}

// Using seekg to move the get pointer


inputFile.seekg(10); // Move the get pointer to the 11th character (0-based indexing)
char ch;
inputFile.get(ch); // Read a character from the new position
std::cout << "Character at position 10: " << ch << std::endl;
// Using seekp to move the put pointer
std::ofstream outputFile2("example.txt", std::ios::app); // Open in append mode
outputFile2.seekp(40); // Move the put pointer to the 41st character
outputFile2 << "appended text"; // Append text at the specified position
outputFile2.close(); // Close the file

// Reopen the file for reading


inputFile.close();
inputFile.open("example.txt");

// Using tellg to get the current position of the get pointer


std::streampos getPosition = inputFile.tellg();
std::cout << "Current position of the get pointer: " << getPosition << std::endl;

// Using tellp to get the current position of the put pointer


std::ofstream outputFile3("example.txt", std::ios::app);
std::streampos putPosition = outputFile3.tellp();
std::cout << "Current position of the put pointer: " << putPosition << std::endl;

// Close the input and output files


inputFile.close();
outputFile3.close();

return 0;
}
TASK
Where will the file pointer point in the following
statement?
infile.seekg(10);

Where will the file pointer point after execution of


the following statement?
ofstream fileout;
fileout.open(“hello”, ios::app);
int p = fileout.tellp();
TASK
Where will the file pointer point in the following
statement?
infile.seekg(10);

The infile.seekg(10); line of code is used to set


the position of the input file stream (infile) to a
specific location in the file. In this case, it's
seeking the position 10 characters from the
beginning of the file. The seekg function is
commonly used for file input streams.
File Pointers
∙ File pointers seekg() and seekp() can also be used with
two arguments:
▫ seekg(offset, refposition);
▫ seekp(offset, refposition);
∙ The parameter offset represents the number of bytes
the file pointer is to be moved from the location
specified by the parameter refposition.
∙ The refposition can take one of the following three
constants defined in the ios class:

▫ ios::beg // start of the file


▫ ios::cur // current position of the pointer
▫ ios::end //end of the file
File Pointers (Pointer Offset calls)
▫ fout.seekg(0,ios::beg); // go to start
▫ fout.seekg(0,ios::cur); // stay at the current position
▫ fout.seekg(0,ios::end); // go to end of the file

▫ fout.seekg(m,ios::beg); // move to (m+1)th byte in the file


//go forward by m byte from the current
▫ fout.seekg(m,ios::cur);
position
// go backward by m bytes from the
▫ fout.seekg(-m,ios::cur);
current position

//go backward by m bytes from


▫ fout.seekg(-m,ios::end);
the end
Sequential Input & Output Operations

∙ The file stream class support a number of


member functions for performing the input and
output operations on files.
▫ put() and get() : used for handling a single
character.
▫ read() and write() : used for handling large blocks
of binary data.
Put() & Get() functions

∙ Function put() writes a single character to


the associated stream.

∙ Function get() reads a single character from the


associated stream.
Put() & Get() functions
#include<iostream> #include<fstream>
#include<string>

int main()
{
char string[80];
cout << “Enter a string :\n ”;
cin >> string;
Put() & Get() functions

int len = strlen(string);


fstream file;
file.open(“Text”, ios::in | ios::out);

for(int i = 0; i < len ; i++) file.put(string[i]);

file.seekg(0);
Put() & Get() functions
char ch;
while(file)
{
file.get(ch);
cout << ch;
}

return 0;
}
Reading & Writing a class object

∙ C cannot handle user defined data types


such as class objects.
∙ C++ provides read() and write() functions to read
and write the objects directly.
∙ The length of the object is obtained using the
sizeof operator.
∙ This length represents the sum total of lengths of all
data members of the object.
Reading & Writing a class object

∙ Syntax:
▫infile.read ((char *) & V, sizeof (V));
▫outfile.write ((char *) & V, sizeof (V));
∙ The first argument is the address of the variable V.
∙ The second is the length of that variable in bytes.
∙ The address of the variable must type cast to char *
(ie: pointer to character type).
Example

#include<iostream.h>
#include<fstream.h> class
inventory
{
char name[10]; int code;
float cost; public:
void readdata(void);
void writedata(void);
};
Example
void inventory :: readdata(void)
{
cout<<“Enter name:”;
cin>> name;
cout<<“Enter code:”;
cin>>code;
cout<<“Enter cost:”; cin>> cost;
}
void inventory :: writedata(void)
{
cout<<name;
cout<<code;
cout<<cost;
}
int main()
{
inventory item[3];
fstream file;
file.open(“Stock.dat”, ios::in | ios::out);
cout<<“Enter the details for three items:”;
for(int i=0; i<3;i++)
{
item[i].readdata();
file.write((char *) & item[i], sizeof(item[i]));
}
Example
file.seekg(0);
for(i=0;i<3;i++)
{
file.read((char *) & item[i], sizeof(item[i]));
item[i].writedata();
}
file.close();
return 0;
}
Updating a File: Random Access

∙ Updating is a routine task in the maintenance of


any data file.
∙ The updating would include one or more of the
following tasks:
▫ Displaying the contents of a file.
▫ Modifying an existing item.
▫ Adding a new item.
▫ Deleting an existing item.
Updating a File: Random Access
∙ The size of each object can be obtained using the
statement:
int obj_len = sizeof(object);
∙ The location of a desired object (say m) is
obtained as:
int location = m * obj_len;
The total number of objects in a file can be
obtained by using object length as:
int n=file_size / obj_len;
Updating a File: Random Access

#include<iostream>
#include<fstream>

class inventory
{
char name[10];
int code;
float cost;
public:
void getdata(void)
{
cout<<“Enter name: ” ;cin>> name;
Updating a File: Random Access
void putdata(void)
{
cout<<name;
cout<<code;
cout<<cost;
}
};

int main()
{
inventory item;
fstream inoutfile;
inoutfile.open(“stock.dat”, ios::ate | ios::in | ios::out|
ios::binary);
Updating a File: Random Access
while(inoutfile.read((char * ) & item, sizeof item))
{
item.putdata();
}
inoutfile.clear(); //turn off EOF flag

cout<<“Add an item:”;
item.getdata();
inoutfile.write((char * ) & item, sizeof item);

inoutfile.seekg(0);
while(inoutfile.read((char * ) & item, sizeof item))
{
item.putdata();
}
Updating a File: Random Access
int last = inoutfile.tellg();
int n = last/sizeof(item);
cout<<“Number of objects:”<<n;
cout<<“Enter the object number to be updated:”;
int object;
cin>> object;
int location = (object-1)* sizeof(item);
inoutfile.seekp(location);
cout<<“Enter the new values of the object:”;
item.getdata();
inoutfile.write((char *) & item, sizeof item);
Updating a File: Random Access
inoutfile.seekg(0);

cout<<“Contents of updated file are:”;


while(inoutfile.read((char * ) & item, sizeof item))
{
item.putdata();
}
inoutfile.close();

return 0;
}
Updating a File: Random Access
Output:
current contents of stock:
AA 11 100
BB 22 200
CC 33 300
Add an item:
Enter name: DD
Enter code: 44
Enter cost: 400
Updating a File: Random Access
Contents of Appended file:

AA 11 100
BB 22 200
CC 33 300
DD 44 400

Number of objects: 4
Enter the object to be updated: 4
Enter new values for object: Enter
name: EE
Enter code: 55 AA 11 100
Enter cost: 500 BB 22 200
Contents of updated file: CC 33 300
EE 55 500
Error Handling During File Operations

∙ Following conditions may arise while dealing with


files:
● A file which we are attempting to open for reading does
not exists.
● The file name used for a new file may already exists.
● We may attempt an invalid operation such as reading past
the end-of-file.
● There may not be any space in the disk for storing more
data.
● We may use invalid file name.
● We may attempt to perform an operation when the file is
not opened for that purpose.
Error Handling During File Operations
∙ The ios class supports several member functions that can
be used to read the status recorded in a file stream.

Function Return value and meaning


eof( ) Returns true (non zero value) if end-of-file is encountered
while reading otherwise returns false (zero).

fail( ) Returns true when an input or output operation has failed.

bad ( ) Returns true if an invalid operation is attempted or any


unrecoverable error has occurred. However, if it is false, it
may be possible to recover from any other error reported,
and continue operation.

good ( ) Returns true if no error has occurred. When is returns false,


no further operations can be carried out.
Error Handling During File Operations
......
......
ifstream infile;
infile.open(“ABC”);
while ( !infile.fail( ))
{
......... ( process the file )
.........
}
if (infile.eof( ) )
{
......... (terminate program normally)
}
else
if(infile.bad ( ))
{
.......... (report fatal error )
}
else
{
infile.clear ( ); // clear error state
.........

}
..........
..........

You might also like