SlideShare una empresa de Scribd logo
1 de 62
Chapter 11
Contents
11.1 Introduction
11.2 Classes for File Stream Operation
11.3 Opening & Closing Files
11.4 Detection of End of File
11.5 More about Open( ): File modes
11.6 File pointer & manipulator
11.7 Sequential Input & output Operation
11.8 Updating a File : Random Access
11.9 Command Line Arguments
2By:-Gourav Kottawar
File Input and Output Stream
 C++ uses file streams as an interface
between the programs and the data
files.
Disk Files Program
Output Stream
Data output
Data input
Input Stream
Write Data
Read Data
3By:-Gourav Kottawar
File Input and Output Stream
Disk Files Program
Output Stream
Data output
Data input
Input Stream
Write Data
Read Data
The stream that
supplies data to the
program is known as
input stream
The stream that
receives data from the
program is known as
output stream
Input stream extracts (or read)
data from file
Output stream inserts (or
writes) data to the file
4By:-Gourav Kottawar
Stream classes for file operations
contained fstream
5By:-Gourav Kottawar
6By:-Gourav Kottawar
7By:-Gourav Kottawar
8By:-Gourav Kottawar
Opening Files
 For opening a file, we must first create a file
stream and then link it to the filename.
 A file stream can be defined using the classes
ifstream, ofstream, and fstream that are
contained in the header file fstream.
 The class to be used depends on read or
write.
 A file can be open in two ways:
Using the constructor function of the class.
○ Useful when we use only one file in the stream.
Using the member function open( ) of the class.
○ Use to manage multiple files using one stream.
9By:-Gourav Kottawar
Opening Files Using Constructor
 This involves two steps:
Create a file stream object to manage the
stream using appropriate class.
○ The class ofstream used to create output
stream.
○ The class ifstream to create input stream.
Initialize the file object with the desired
filename.
10By:-Gourav Kottawar
Opening Files Using Constructor
 ofstream outfile (“results”);
 ifstream infile(“data”);
continue …
Program
Output Stream
outfile
infile
Input Stream
Disk
Result
File
Data
File
11By:-Gourav Kottawar
Opening Files Using Open( )
 The open( ) can be used to open
multiple files that use the same stream
object.
 For processing a set files sequentially.
file-stream-class stream-object;
stream-object.open ( “file_name” );
12By:-Gourav Kottawar
Opening Files Using Open( )
ofstream outfile;
outfile.open(“DATA1”);
……..
outfile.close( );
outfile.open(“DATA2”);
………
outfile.close( );
.........
 The above program segment opens two files in
sequence for writing the data.
 The first file is closed before opening the second one.
 A stream can be connected to only one file at a time.
continue …
13By:-Gourav Kottawar
Opening file using constructor
14By:-Gourav Kottawar
15By:-Gourav Kottawar
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<fstream.h>
void main()
{
char c,fname[10];
ofstream out;
cout<<"Enter File name:";
cin>>fname;
out.open(fname);
cout<<"Enter contents to store in file (Enter # at end):n";
while((c=getchar())!='#')
{
out<<c;
}
out.close();
getch();
}
Opening file using open()
16By:-Gourav Kottawar
// Creating file with constructor
#include<iostream.h>
#include<fstream.h>
int main()
{
ofstream outf(“Product”);
cout<<“|n Enetr product name:”;
char name[20];
cin>>name;
outf<<name<<“n”;
cout<<“Enter item cost”;
float cost;
cin>>cost;
outf<<cost <<“n”;
outf.close();
ifsteam inf(“Product”);
inf>>name;
inf>>cost;
cout<<endl;
cout<<“Item name :”<<name <<endl;
cout<<“Item cost :”<<cost<<“n”;
inf.close();
}
17By:-Gourav Kottawar
// Creating file with constructor
#include<iostream.h>
#include<fstream.h>
int main()
{
ofstream outf(“Product”);
cout<<“|n Enetr product name:”;
char name[20];
cin>>name;
outf<<name<<“n”;
cout<<“Enter Product cost”;
float cost;
cin>>cost;
outf<<cost <<“n”;
outf.close();
ifsteam inf(“Product”);
inf>>name;
inf>>cost;
cout<<endl;
cout<<“Product name :”<<name <<endl;
cout<<“IProduct cost :” <<cost<<“n”;
inf.close();
}
//Output
Enter product name : HDD
Enter product cost : 4000
Product Name :HDD
Product cost :4000
18By:-Gourav Kottawar
#include<iostream.h>
#inlcude<fstream.h>
int main()
{
Ofstream fout;
fout.open(“Brand”);
fout<<“Marutin”;
fout<<“Volks n”;
fout<<“Hondan”;
fout.close();
fout.open(“Car”);
fout<<“Swiftn”;
fout<<“Polon”;
fout<<“Amazen”;
fout..close();
//Reading the files
Const int N = 80;
Chat line[N];
ifstream fin;
fin.open(“Brand”);
cout<<“nContents of Brand filen”;
while(fin)
{
fin.getline(line,N);
cout<<line;
}
fin.close();
fin.open(“Car”);
cout<<“n Contents of carfile n”;
while(fin)
{
fin.getline(line,N);
cout<<line;
}
fin.close();
return 0;
}
19By:-Gourav Kottawar
//Reads the files
#include <iostream.h>
#include<fstream.h>
#include<stdlib.h>
int main()
{
const int SIZE = 80;
char line[SIZE];
ifstream fin1,fin2;
fin1.open(“Brand”);
fin2.open(“Car”);
for(int i= 1;i<=10;i++)
{
if(fin1.eof()!=0)
{ cout<<“Exit from Brand n”);
exit(1);
}
fin1.getline(line,SIZE);
cout<<“Car of “<<line;
if(fin2.eof() !=0)
{
cout<<“Exit from Car”;
exit(1);
} 20By:-Gourav Kottawar
fin2.getline(line,SIZE);
cout<<line<<“n”;
}
return 0;
}
21By:-Gourav Kottawar
fin2.getline(line,SIZE);
cout<<line<<“n”;
}
return 0;
}
//Output
Car of Maruti
Swift
Car of Volks wagan
Polo
Car of Honda
Amaze
22By:-Gourav Kottawar
Detecting End-Of-File
 while (fin)
An ifstream object fin returns a value 0 if any error
occurs in the file operation including the end-of-file
condition.
So the while loop may terminates when fin returns a
value of zero on reaching the end-of-file condition.
 if(fin1.eof() != 0) {exit(1);}
eof( ) is a member of ios class.
It returns a non-zero value if the end-of-file (EOF)
condition is encountered, and a zero, otherwise.
23By:-Gourav Kottawar
File Modes
 stream-object.open(“file_name”, mode);
The second argument mode specifies the
purpose for which the file is opened.
Default values for these second parameters:
○ ios::in – for ifstream - reading only
○ ios::out – for ofstream - writing only
24By:-Gourav Kottawar
File Modes
 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
exist
 ios::noreplace  Open files if the file already
exists
 ios::out  Open file for writing only
 ios::trunc  Delete the contents of the file if it exists
fout.open(“data”, ios::app | ios :: nocreate)
continue …
25By:-Gourav Kottawar
File Pointer
 Input Pointer (get pointer)
The input pointer is used for reading contents of
a given file location.
 Output Pointer (put pointer)
The output pointer is used for writing to a given
file location.
 Each time an input or output operation
takes place, the appropriate pointer is
automatically advanced.
26By:-Gourav Kottawar
File Pointer – Default Actions
 When a file opened in read-only mode, the
input pointer is automatically set at the
beginning of the file.
 When a file is opened in write-only mode, the
existing contents are deleted and the output
pointer is set at the beginning.
 When a file is opened in append mode, the
output pointer moves to the end of file.
27By:-Gourav Kottawar
Functions for Manipulations of 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.
28By:-Gourav Kottawar
Seek Function with Absolute Position
 infile.seekg(10);
Moves the file pointer to the byte number 10.
The bytes in a file are numbered beginning
from zero. Therefore, the pointer pointing to
the 11th
byte in the file.
29By:-Gourav Kottawar
Seek Function with Specifying the Offset
 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 takes 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
30By:-Gourav Kottawar
Seek Function with Specifying the Offset
fout.seekg(0, ios : : beg);fout.seekg(0, ios : : beg); Go to startGo to start
fout.seekg(0, ios : : cur);fout.seekg(0, ios : : cur); Stay at the current positionStay at the current position
fout.seekg(0, ios : : end);fout.seekg(0, ios : : end); Go to the end of fileGo to the end of file
fout.seekg(m, ios : : beg);fout.seekg(m, ios : : beg); Move to (m+1)th byte in the fileMove to (m+1)th byte in the file
fout.seekg(m, ios : : cur);fout.seekg(m, ios : : cur); Go forward by m bytes from the current positionGo forward by m bytes from the current position
fout.seekg(-m, ios : : cur);fout.seekg(-m, ios : : cur); Go backward by m bytes from the current positionGo backward by m bytes from the current position
fout.seekg(-m, ios : : end)fout.seekg(-m, ios : : end) Go backward by m bytes from the endGo backward by m bytes from the end
31By:-Gourav Kottawar
Sequential Input and Output Operations
 put( ) and get( ) Functions
The function put( ) writes a single character
to the associated stream.
The function get( ) reads a single charracter
from the associated stream.
32By:-Gourav Kottawar
33By:-Gourav Kottawar
//output
File will be created at
C:TurboC++DiskTurboC3BINABC
34By:-Gourav Kottawar
Sequential Input and Output Operations
 write( ) and read( ) Functions
The functions write( ) and read ( ) handle the data
in binary form.
The values are stored in the disk file in the same
format in which they are stored in the internal
memory.
An int takes two bytes to store its value in the
binary form, irrespective of its size.
But a 4 digit int will take four bytes to store it in
the character form.
continue …
35By:-Gourav Kottawar
Sequential Input and Output Operations
Representing 2594
continue …
0 0 1 0 0 0 1 00 0 0 0 1 0 1 0
4952
Binary Format
Character Format
4 Bytes II
2 Bytes II
36By:-Gourav Kottawar
Sequential Input and Output Operations
 infile.read((char *) &V, sizeof(V));
 outfile.write((char *) &V, sizeof(V));
 write( ) and read( ) functions take two
arguments.
 First is the address of the variable V
 Second is the length of that variable in bytes.
 The address of the variable must be cast to
type char * (pointer to character type).
continue …
37By:-Gourav Kottawar
38By:-Gourav Kottawar
39By:-Gourav Kottawar
Reading and Writing a Class Object
 The read( ) and write( ) are also used to read
from or write to the disk files objects directly.
 The read( ) and write( ) handle the entire
structure of an object as a single unit, using
the computer’s internal representation of
data.
 Only data members are written to the disk
files.
40By:-Gourav Kottawar
41By:-Gourav Kottawar
42By:-Gourav Kottawar
43By:-Gourav Kottawar
Updating A File : Random Access
 The size of each object can be obtained using the
statement
int object_length = sizeof(object);
 The location of a desired object, say mth object
int location = m * object_length;
The location gives the byte number of the first byte of
the mth object.
 Now we can use seekg( ) or seekp( ) to set the file
pointer to reach this byte.
44By:-Gourav Kottawar
Updating A File : Random Access
 To find the total number of objects in a file using
object_length
int n = file_size / object_length;
 The file size can be obtained using the function tellg( )
or tellp( ) when the pointer is located at the end of the
file.
continue …
45By:-Gourav Kottawar
46By:-Gourav Kottawar
47By:-Gourav Kottawar
48By:-Gourav Kottawar
49By:-Gourav Kottawar
Error Handling During File Operations
 A file which we are attempting to open for reading does
not exist.
 The file name used for a new file may already exist.
 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 an invalid file name.
 We may attempt to perform an operation when the file is
not opened for that purpose.
50By:-Gourav Kottawar
Error Handling During File Operations
 The C++ file stream inherits a “stream_state” member
from the class ios.
 This member records information on the status of a file
that is being currently used.
 The class ios supports several member functions that
can be used to read the status recorded in a file stream.
 eof( )
 fail( )
 bad( )
 good( ), etc.
continue …
51By:-Gourav Kottawar
Command – Line Arguments
 C++ supports a feature that facilitates the supply of
argument to the main( ) function.
 These arguments are supplied at the time of invoking
the program.
 They are typically used to pass the names of data files.
 Eg:- exam data result
 The command-line arguments are typed by the user and
are delimited by a space.
52By:-Gourav Kottawar
Command – Line Arguments
 The main function can take two arguments.
 main( int argc, char * argv [ ] )
 The first argument argc (argument counter) represents
the number of arguments in the command line.
 The second argument argv (argument vector) is an
array of char type pointers that points to the command
line arguments.
 The size of the array will be equal to the value of argc.
continue …
53By:-Gourav Kottawar
Command – Line Arguments
 C:> exam data results
 The value of argc would be 3 and argv would be an
array of three pointers to strings as:
 argv[0]  exam
 argv[1]  data
 argv[2]  results
○ ……
○ ……
○ infile.open(argv[1]);
○ ……
○ ……
○ outfile.open(argv[2]);
○ ……
continue …
54By:-Gourav Kottawar
#include <iostream>
int main(int argc, char *argv[])
{
using namespace std;
cout << "There are " << argc << " arguments:" << endl;
// Loop through each argument and print its number and value
for (int nArg=0; nArg < argc; nArg++)
cout << nArg << " " << argv[nArg] << endl;
return 0;
}
55By:-Gourav Kottawar
#include <iostream>
int main(int argc, char *argv[])
{
using namespace std;
cout << "There are " << argc << " arguments:" << endl;
// Loop through each argument and print its number and value
for (int nArg=0; nArg < argc; nArg++)
cout << nArg << " " << argv[nArg] << endl;
return 0;
}
//output
56By:-Gourav Kottawar
57By:-Gourav Kottawar
58By:-Gourav Kottawar
59By:-Gourav Kottawar
60By:-Gourav Kottawar
61By:-Gourav Kottawar
Thank You

Más contenido relacionado

La actualidad más candente

Linux booting procedure
Linux booting procedureLinux booting procedure
Linux booting procedure
Dhaval Kaneria
 

La actualidad más candente (20)

File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Ipc in linux
Ipc in linuxIpc in linux
Ipc in linux
 
File handling in C
File handling in CFile handling in C
File handling in C
 
File operations in c
File operations in cFile operations in c
File operations in c
 
Mutual exclusion and sync
Mutual exclusion and syncMutual exclusion and sync
Mutual exclusion and sync
 
File handling-c
File handling-cFile handling-c
File handling-c
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Storage classes in c language
Storage classes in c languageStorage classes in c language
Storage classes in c language
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Chapter 15 - Security
Chapter 15 - SecurityChapter 15 - Security
Chapter 15 - Security
 
Friend function
Friend functionFriend function
Friend function
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C++ How to program
C++ How to programC++ How to program
C++ How to program
 
Linux booting procedure
Linux booting procedureLinux booting procedure
Linux booting procedure
 

Similar a working file handling in cpp overview

Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
Working with file(35,45,46)
Working with file(35,45,46)Working with file(35,45,46)
Working with file(35,45,46)
Dishant Modi
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
Deepak Singh
 
file handling c++
file handling c++file handling c++
file handling c++
Guddu Spy
 

Similar a working file handling in cpp overview (20)

File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
cpp-file-handling
cpp-file-handlingcpp-file-handling
cpp-file-handling
 
Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
 
Data file handling
Data file handlingData file handling
Data file handling
 
Filehandling
FilehandlingFilehandling
Filehandling
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
Working with file(35,45,46)
Working with file(35,45,46)Working with file(35,45,46)
Working with file(35,45,46)
 
working with files
working with filesworking with files
working with files
 
File Pointers
File PointersFile Pointers
File Pointers
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
File Handling
File HandlingFile Handling
File Handling
 
file handling c++
file handling c++file handling c++
file handling c++
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 

Más de gourav kottawar

Más de gourav kottawar (20)

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
classes & objects in cpp
classes & objects in cppclasses & objects in cpp
classes & objects in cpp
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
pointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpppointers, virtual functions and polymorphisms in c++ || in cpp
pointers, virtual functions and polymorphisms in c++ || in cpp
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
 
basics of c++
basics of c++basics of c++
basics of c++
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
expression in cpp
expression in cppexpression in cpp
expression in cpp
 
SQL || overview and detailed information about Sql
SQL || overview and detailed information about SqlSQL || overview and detailed information about Sql
SQL || overview and detailed information about Sql
 
SQL querys in detail || Sql query slides
SQL querys in detail || Sql query slidesSQL querys in detail || Sql query slides
SQL querys in detail || Sql query slides
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
 
overview of database concept
overview of database conceptoverview of database concept
overview of database concept
 
Relational Model in dbms & sql database
Relational Model in dbms & sql databaseRelational Model in dbms & sql database
Relational Model in dbms & sql database
 
DBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) pptDBMS information in detail || Dbms (lab) ppt
DBMS information in detail || Dbms (lab) ppt
 
security and privacy in dbms and in sql database
security and privacy in dbms and in sql databasesecurity and privacy in dbms and in sql database
security and privacy in dbms and in sql database
 

Último

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

working file handling in cpp overview

  • 2. Contents 11.1 Introduction 11.2 Classes for File Stream Operation 11.3 Opening & Closing Files 11.4 Detection of End of File 11.5 More about Open( ): File modes 11.6 File pointer & manipulator 11.7 Sequential Input & output Operation 11.8 Updating a File : Random Access 11.9 Command Line Arguments 2By:-Gourav Kottawar
  • 3. File Input and Output Stream  C++ uses file streams as an interface between the programs and the data files. Disk Files Program Output Stream Data output Data input Input Stream Write Data Read Data 3By:-Gourav Kottawar
  • 4. File Input and Output Stream Disk Files Program Output Stream Data output Data input Input Stream Write Data Read Data The stream that supplies data to the program is known as input stream The stream that receives data from the program is known as output stream Input stream extracts (or read) data from file Output stream inserts (or writes) data to the file 4By:-Gourav Kottawar
  • 5. Stream classes for file operations contained fstream 5By:-Gourav Kottawar
  • 9. Opening Files  For opening a file, we must first create a file stream and then link it to the filename.  A file stream can be defined using the classes ifstream, ofstream, and fstream that are contained in the header file fstream.  The class to be used depends on read or write.  A file can be open in two ways: Using the constructor function of the class. ○ Useful when we use only one file in the stream. Using the member function open( ) of the class. ○ Use to manage multiple files using one stream. 9By:-Gourav Kottawar
  • 10. Opening Files Using Constructor  This involves two steps: Create a file stream object to manage the stream using appropriate class. ○ The class ofstream used to create output stream. ○ The class ifstream to create input stream. Initialize the file object with the desired filename. 10By:-Gourav Kottawar
  • 11. Opening Files Using Constructor  ofstream outfile (“results”);  ifstream infile(“data”); continue … Program Output Stream outfile infile Input Stream Disk Result File Data File 11By:-Gourav Kottawar
  • 12. Opening Files Using Open( )  The open( ) can be used to open multiple files that use the same stream object.  For processing a set files sequentially. file-stream-class stream-object; stream-object.open ( “file_name” ); 12By:-Gourav Kottawar
  • 13. Opening Files Using Open( ) ofstream outfile; outfile.open(“DATA1”); …….. outfile.close( ); outfile.open(“DATA2”); ……… outfile.close( ); .........  The above program segment opens two files in sequence for writing the data.  The first file is closed before opening the second one.  A stream can be connected to only one file at a time. continue … 13By:-Gourav Kottawar
  • 14. Opening file using constructor 14By:-Gourav Kottawar
  • 16. #include<iostream.h> #include<stdio.h> #include<conio.h> #include<fstream.h> void main() { char c,fname[10]; ofstream out; cout<<"Enter File name:"; cin>>fname; out.open(fname); cout<<"Enter contents to store in file (Enter # at end):n"; while((c=getchar())!='#') { out<<c; } out.close(); getch(); } Opening file using open() 16By:-Gourav Kottawar
  • 17. // Creating file with constructor #include<iostream.h> #include<fstream.h> int main() { ofstream outf(“Product”); cout<<“|n Enetr product name:”; char name[20]; cin>>name; outf<<name<<“n”; cout<<“Enter item cost”; float cost; cin>>cost; outf<<cost <<“n”; outf.close(); ifsteam inf(“Product”); inf>>name; inf>>cost; cout<<endl; cout<<“Item name :”<<name <<endl; cout<<“Item cost :”<<cost<<“n”; inf.close(); } 17By:-Gourav Kottawar
  • 18. // Creating file with constructor #include<iostream.h> #include<fstream.h> int main() { ofstream outf(“Product”); cout<<“|n Enetr product name:”; char name[20]; cin>>name; outf<<name<<“n”; cout<<“Enter Product cost”; float cost; cin>>cost; outf<<cost <<“n”; outf.close(); ifsteam inf(“Product”); inf>>name; inf>>cost; cout<<endl; cout<<“Product name :”<<name <<endl; cout<<“IProduct cost :” <<cost<<“n”; inf.close(); } //Output Enter product name : HDD Enter product cost : 4000 Product Name :HDD Product cost :4000 18By:-Gourav Kottawar
  • 19. #include<iostream.h> #inlcude<fstream.h> int main() { Ofstream fout; fout.open(“Brand”); fout<<“Marutin”; fout<<“Volks n”; fout<<“Hondan”; fout.close(); fout.open(“Car”); fout<<“Swiftn”; fout<<“Polon”; fout<<“Amazen”; fout..close(); //Reading the files Const int N = 80; Chat line[N]; ifstream fin; fin.open(“Brand”); cout<<“nContents of Brand filen”; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); fin.open(“Car”); cout<<“n Contents of carfile n”; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); return 0; } 19By:-Gourav Kottawar
  • 20. //Reads the files #include <iostream.h> #include<fstream.h> #include<stdlib.h> int main() { const int SIZE = 80; char line[SIZE]; ifstream fin1,fin2; fin1.open(“Brand”); fin2.open(“Car”); for(int i= 1;i<=10;i++) { if(fin1.eof()!=0) { cout<<“Exit from Brand n”); exit(1); } fin1.getline(line,SIZE); cout<<“Car of “<<line; if(fin2.eof() !=0) { cout<<“Exit from Car”; exit(1); } 20By:-Gourav Kottawar
  • 22. fin2.getline(line,SIZE); cout<<line<<“n”; } return 0; } //Output Car of Maruti Swift Car of Volks wagan Polo Car of Honda Amaze 22By:-Gourav Kottawar
  • 23. Detecting End-Of-File  while (fin) An ifstream object fin returns a value 0 if any error occurs in the file operation including the end-of-file condition. So the while loop may terminates when fin returns a value of zero on reaching the end-of-file condition.  if(fin1.eof() != 0) {exit(1);} eof( ) is a member of ios class. It returns a non-zero value if the end-of-file (EOF) condition is encountered, and a zero, otherwise. 23By:-Gourav Kottawar
  • 24. File Modes  stream-object.open(“file_name”, mode); The second argument mode specifies the purpose for which the file is opened. Default values for these second parameters: ○ ios::in – for ifstream - reading only ○ ios::out – for ofstream - writing only 24By:-Gourav Kottawar
  • 25. File Modes  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 exist  ios::noreplace  Open files if the file already exists  ios::out  Open file for writing only  ios::trunc  Delete the contents of the file if it exists fout.open(“data”, ios::app | ios :: nocreate) continue … 25By:-Gourav Kottawar
  • 26. File Pointer  Input Pointer (get pointer) The input pointer is used for reading contents of a given file location.  Output Pointer (put pointer) The output pointer is used for writing to a given file location.  Each time an input or output operation takes place, the appropriate pointer is automatically advanced. 26By:-Gourav Kottawar
  • 27. File Pointer – Default Actions  When a file opened in read-only mode, the input pointer is automatically set at the beginning of the file.  When a file is opened in write-only mode, the existing contents are deleted and the output pointer is set at the beginning.  When a file is opened in append mode, the output pointer moves to the end of file. 27By:-Gourav Kottawar
  • 28. Functions for Manipulations of 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. 28By:-Gourav Kottawar
  • 29. Seek Function with Absolute Position  infile.seekg(10); Moves the file pointer to the byte number 10. The bytes in a file are numbered beginning from zero. Therefore, the pointer pointing to the 11th byte in the file. 29By:-Gourav Kottawar
  • 30. Seek Function with Specifying the Offset  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 takes 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 30By:-Gourav Kottawar
  • 31. Seek Function with Specifying the Offset fout.seekg(0, ios : : beg);fout.seekg(0, ios : : beg); Go to startGo to start fout.seekg(0, ios : : cur);fout.seekg(0, ios : : cur); Stay at the current positionStay at the current position fout.seekg(0, ios : : end);fout.seekg(0, ios : : end); Go to the end of fileGo to the end of file fout.seekg(m, ios : : beg);fout.seekg(m, ios : : beg); Move to (m+1)th byte in the fileMove to (m+1)th byte in the file fout.seekg(m, ios : : cur);fout.seekg(m, ios : : cur); Go forward by m bytes from the current positionGo forward by m bytes from the current position fout.seekg(-m, ios : : cur);fout.seekg(-m, ios : : cur); Go backward by m bytes from the current positionGo backward by m bytes from the current position fout.seekg(-m, ios : : end)fout.seekg(-m, ios : : end) Go backward by m bytes from the endGo backward by m bytes from the end 31By:-Gourav Kottawar
  • 32. Sequential Input and Output Operations  put( ) and get( ) Functions The function put( ) writes a single character to the associated stream. The function get( ) reads a single charracter from the associated stream. 32By:-Gourav Kottawar
  • 34. //output File will be created at C:TurboC++DiskTurboC3BINABC 34By:-Gourav Kottawar
  • 35. Sequential Input and Output Operations  write( ) and read( ) Functions The functions write( ) and read ( ) handle the data in binary form. The values are stored in the disk file in the same format in which they are stored in the internal memory. An int takes two bytes to store its value in the binary form, irrespective of its size. But a 4 digit int will take four bytes to store it in the character form. continue … 35By:-Gourav Kottawar
  • 36. Sequential Input and Output Operations Representing 2594 continue … 0 0 1 0 0 0 1 00 0 0 0 1 0 1 0 4952 Binary Format Character Format 4 Bytes II 2 Bytes II 36By:-Gourav Kottawar
  • 37. Sequential Input and Output Operations  infile.read((char *) &V, sizeof(V));  outfile.write((char *) &V, sizeof(V));  write( ) and read( ) functions take two arguments.  First is the address of the variable V  Second is the length of that variable in bytes.  The address of the variable must be cast to type char * (pointer to character type). continue … 37By:-Gourav Kottawar
  • 40. Reading and Writing a Class Object  The read( ) and write( ) are also used to read from or write to the disk files objects directly.  The read( ) and write( ) handle the entire structure of an object as a single unit, using the computer’s internal representation of data.  Only data members are written to the disk files. 40By:-Gourav Kottawar
  • 44. Updating A File : Random Access  The size of each object can be obtained using the statement int object_length = sizeof(object);  The location of a desired object, say mth object int location = m * object_length; The location gives the byte number of the first byte of the mth object.  Now we can use seekg( ) or seekp( ) to set the file pointer to reach this byte. 44By:-Gourav Kottawar
  • 45. Updating A File : Random Access  To find the total number of objects in a file using object_length int n = file_size / object_length;  The file size can be obtained using the function tellg( ) or tellp( ) when the pointer is located at the end of the file. continue … 45By:-Gourav Kottawar
  • 50. Error Handling During File Operations  A file which we are attempting to open for reading does not exist.  The file name used for a new file may already exist.  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 an invalid file name.  We may attempt to perform an operation when the file is not opened for that purpose. 50By:-Gourav Kottawar
  • 51. Error Handling During File Operations  The C++ file stream inherits a “stream_state” member from the class ios.  This member records information on the status of a file that is being currently used.  The class ios supports several member functions that can be used to read the status recorded in a file stream.  eof( )  fail( )  bad( )  good( ), etc. continue … 51By:-Gourav Kottawar
  • 52. Command – Line Arguments  C++ supports a feature that facilitates the supply of argument to the main( ) function.  These arguments are supplied at the time of invoking the program.  They are typically used to pass the names of data files.  Eg:- exam data result  The command-line arguments are typed by the user and are delimited by a space. 52By:-Gourav Kottawar
  • 53. Command – Line Arguments  The main function can take two arguments.  main( int argc, char * argv [ ] )  The first argument argc (argument counter) represents the number of arguments in the command line.  The second argument argv (argument vector) is an array of char type pointers that points to the command line arguments.  The size of the array will be equal to the value of argc. continue … 53By:-Gourav Kottawar
  • 54. Command – Line Arguments  C:> exam data results  The value of argc would be 3 and argv would be an array of three pointers to strings as:  argv[0]  exam  argv[1]  data  argv[2]  results ○ …… ○ …… ○ infile.open(argv[1]); ○ …… ○ …… ○ outfile.open(argv[2]); ○ …… continue … 54By:-Gourav Kottawar
  • 55. #include <iostream> int main(int argc, char *argv[]) { using namespace std; cout << "There are " << argc << " arguments:" << endl; // Loop through each argument and print its number and value for (int nArg=0; nArg < argc; nArg++) cout << nArg << " " << argv[nArg] << endl; return 0; } 55By:-Gourav Kottawar
  • 56. #include <iostream> int main(int argc, char *argv[]) { using namespace std; cout << "There are " << argc << " arguments:" << endl; // Loop through each argument and print its number and value for (int nArg=0; nArg < argc; nArg++) cout << nArg << " " << argv[nArg] << endl; return 0; } //output 56By:-Gourav Kottawar