SlideShare ist ein Scribd-Unternehmen logo
1 von 39
WORKING WITH FILE
By Hansa Halai
 Many real life problems handle large volume of data and in
such situation we need to use some devices such as floppy
disk or hard disk to store data.
 The data is stored in these devices using the concept of
file.
 A File is a collection of related data stored in a particular
area on the disk.
 Program can be designed to perform the read and write
operations on these files.
 The program can be involves either or both kind of data
communications:
a. Data transfer between the console unit and the
program.
b. Data transfer between the program and the disk file.
By Hansa Halai
 The I/O System of c++ handles the file operations which
is very much similar to the console input and output
operation.
 It uses file stream as an interface between the
program and the files.
 The stream that supplies data to program is known as
input stream.
 The stream that receives data from the program is
known as output stream.
 In other word, the input stream extracts (or read) data
from file and the output stream insert (or write) data to
file.
By Hansa Halai
By Hansa Halai
CLASSES FOR FILE STREAM OPERATION:
There are three file I/O classes used for read/write
operations:
 ifstream: can be used to read operations.
 ofstream: can be used to write operations.
 fstream: can be used for both read and write
operations.
 fstreambase: serves as base for fstream,
ofstream, ifstream.
By Hansa Halai
By Hansa Halai
OPENING AND CLOSING FILE:
 If we want to use a disk file, we need to decide the
following things about the file and its intended use:
1. Suitable name for the file.
2. Data type and structure.
3. Purpose.
4. Opening method.
 For opening, 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 contain in the header file fstream.
 A file can be opened in two ways:
1. Using the constructor function of the class.
2. Using the method function open() of the class.
By Hansa Halai
The first method is useful when we use only one file in the stream.
The second method is used when we want to manage multiple file
using one stream.
 Opening file using constructor:
As we know that a constructor is used to initialize an object while
it is being created. here, a file name is used to initialize the file
stream object.
This involves following steps:
1. Create a file stream object to manage the stream using the
appropriate class. That is to say, the class ofstream is used to
create the output stream and ifstream to create the input
stream.
2. Initialize the file object with the desired filename.
For Ex: ofstream outfile(“file1”);
By Hansa Halai
By Hansa Halai
EXAMPLE:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream outf("ITEM"); //connect item file to outf
cout<<"Enter Item name: ";
char name[10];
cin>>name;
outf<<name<<"n"; //write in file ITEM
cout<<"Enter Item cost: ";
float price;
cin>>price;
outf<<price<<"n";
By Hansa Halai
outf.close();
ifstream inf("ITEM");
inf>>name; // read name from file
inf>>price;
cout<<"n";
cout<<"Item Name: "<<name<<"n";
cout<<"Item Price: "<<price<<"n";
inf.close();
return 0;
}
By Hansa Halai
Read data from file.
The created file is stored in a place
where the program is saved.
OPENING FILE USING OPEN() METHOD:
The open() function is used to open multiple files that use the same
stream object.
 Syntax:
file_stream_class stream_object;
stream_object.open(“filename”);
 Ex:
ofstream ofile;
ofile.open(“file1”);
…
…
ofile.close();
ofile.open(“file2”);
…
…
ofile.close();
By Hansa Halai
 Note that the first file is closed before the second file is open.
This is necessary because a stream can be connected to only
one file at a time.
 Example:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream file1_out;
file1_out.open("Country");
file1_out<<"India"<<endl;
file1_out<<"UK"<<endl;
file1_out<<"USA"<<endl;
file1_out.close();
By Hansa Halai
file1_out.open("capital");
file1_out<<"Delhi"<<endl;
file1_out<<"London"<<endl;
file1_out<<"Washington"<<endl;
file1_out.close();
const int n=80;
char line[n];
ifstream file1_in;
file1_in.open("Country");
cout<<"Content of the country file.. n“;
while(file1_in)
{
file1_in.getline(line,n);
cout<<"n";
cout<<line;
}
By Hansa Halai
file1_in.close();
file1_in.open("capital");
cout<<"nContent of the capital file..n ";
while(file1_in)
{
file1_in.getline(line,n);
cout<<"n";
cout<<line;
}
file1_in.close();
return 0;
}
o Output:
By Hansa Halai
READING FROM TWO FILES SIMULTANEOUSLY:
 Example:
#include<iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
int main()
{
const int size = 50;
char line[size];
ifstream fin1,fin2;
fin1.open("country");
fin2.open("capital");
By Hansa Halai
for(int i=1;i<=3;i++)
{
if(fin1.eof()!=0)
{
cout<<"Exit from country file..n";
exit(1);
}
fin1.getline(line,size);
cout<<"nCapital of "<<line<<endl;
if(fin2.eof()!=0)
{
cout<<"nExit from capital file..";
exit(1);
}
fin2.getline(line,size);
cout<<" "<<line<<"n";
}
return 0;
}
By Hansa Halai
DETECTING END-OF-FILE:
 Detection of the end-of-file condition is necessary for
preventing any further attempt to read data from the file.
We can achieve this by using following two statement:
 1) while (file_stream_object)
Ex: while(fin)
The while loop terminates when fin object returns a value
of zero or reaching at the end-of-file.
2) if(fin.eof()!=0)
{
exit(1);
}
 The eof() is a member function of ios class. It returns a non-
zero value if the end-of-file condition encountered. Therefore ,
the statement terminates the program on reaching the end of
file.
By Hansa Halai
FILE MODES:
 We have used ifstream and ofstream constructor and
open() method to create a new file or open a existing file.
By Hansa Halai
File Type Default Open Mode
ofstream
The file is opened for output only. (Information may be
written to the file, but not read from the file.) If the file does
not exist, it is created. If the file already exists, its contents
are deleted (the file is truncated).
ifstream
The file is opened for input only. (Information may be
read from the file, but not written to it.) The file’s contents
will be read from its beginning. If the file does not exist, the
open function fails.
 In both these methods, we used only one argument list that was
file name.
 open() can also take two arguments, the second one
specifying the file mode.
 syntax:
stream_object.open(“file_name”,mode);
 Ex:
fout.open(“student”,ios::out) ;
 The prototype of these class member functions contains default
value for second argument and therefore they use the default
value in absence of the actual values. The default values as
follows:
ios::in – For ifstream function meaning open for reading only.
ios::out – For ofstream function meaning open for writing only.
By Hansa Halai
By Hansa Halai
File Mode Flag Meaning
ios::app
Append mode. If the file already exists, its contents are
preserved and all output is written to the end of the file. By
default, this flag causes the file to be created if it does not
exist.
ios::ate
If the file already exists, the program goes directly to
the end of it. Output may be written anywhere in the file.
ios::binary
Binary mode. When a file is opened in binary mode,
information is written to or read from it in pure binary format.
(The default mode is text.)
ios::in
Input mode. Information will be read from the file. If the
file does not exist, it will not be created and the open
function will fail.
By Hansa Halai
File Mode
Flag
Meaning
ios::nocreate If the file does not already exist,
this flag will cause the open function
to fail. (The file will not be
created.)
ios::noreplace If the file already exists, this flag
will cause the open function to fail.
(The existing file will not be
opened.)
ios::out Output mode. Information will be
written to the file. By default, the
file’s contents will be deleted if it
already exists.
ios::trunc If the file already exists, its
contents will be deleted (truncated).
This is the default mode used by
ios::out.
FILE POINTER AND THEIR MANIPULATIONS:
 Each file has two associated pointer known as the file
pointers. one of them is called input pointer or get
pointer and other is called the output pointer or put
pointer.
 The input pointer is used for reading the content of
given file location and output pointer is used for writing
to a given file location.
 Each time an input and output operation takes place,
the appropriate pointer is automatically advanced.
By Hansa Halai
 Default action:
When we open file in read only mode the input pointer
automatically set at the beginning so that we can read the
file from start.
When we open file in write only mode the input pointer
the existing contents are deleted and the output pointer is
set at the beginning. This enables us to write the file from
start.
By Hansa Halai
By Hansa Halai
In case we want to open an existing file to add more
data, the file is opened in “append” mode, which is move
file pointer at the end of file.
 Functions for manipulation of file pointer:
 As we shown file pointer takes place automatically by
default. But how do we move a file pointer to any other
desired location. This is possible only if we can take
control of movement of file pointers ourselves.
 The File stream classes support the following function
to manage such situation:
 seekg(): Move get pointer to specific location.(read)
 seekp():Move put pointer to specific location.(write)
 tellg(): Gives the current position of the get pointer.
 tellp():Gives the current position of the put pointer.
By Hansa Halai
 Example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream dataFile("sentence.txt", ios::out);
char ch;
cout << "Type a sentence and be sure to end it with a ";
cout << "period.n";
while (1)
{
cin.get(ch);
dataFile.put(ch);
if (ch == '.')
break;
}
By Hansa Halai
dataFile.close();
dataFile.open("sentence.txt", ios::in);
char c;
dataFile.seekg(3L, ios::beg);
dataFile.get(c);
cout << "nByte 3 from beginning: " << c << endl;
dataFile.seekg(-5L, ios::end);
dataFile.get(c);
cout << "nByte 5 from end: " << c << endl;
dataFile.close();
}
By Hansa Halai
 Example-2:
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ofstream outf("test");
cout<<"Enter String: ";
char str[20];
cin>>str;
outf<<str;
cout<<"n";
int p=outf.tellp();
cout<<"size of file:"<<p;
outf.close();
By Hansa Halai
Represent the number of bytes in the file
ifstream inf;
inf.open("test");
cout<<"n";
cout<<"nString is: "<<str<<"n";
inf>>str;
inf.close();
return 0;
}
By Hansa Halai
 Specifying the offset:
We have just seen how to move a file pointer to a desired
location using the seek function. The argument to these functions
represents the absolute position in the file.
 Seekg() and seekp() can also be used with two arguments as
follows:
seekg(offset,refposition);
seekp(offset,refposition);
By Hansa Halai
 The parameter offset represent 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
Ex: (In File pointer and their Manipulations Ex-1)
By Hansa Halai
SEQUENTIAL INPUT AND OUTPUT OPERATIONS:
 The file stream classes support a number of
member functions for performing the input and
output operation on file.
 One pair of the function get() and put() are
designed for handling a single character at a time.
 Another pair of functions write() and read() are
designed to write and read block of binary data.
By Hansa Halai
 put() and get() function:
• The function put() writes a single character to associated
stream.
• The function get() reads a single character from associated
stream .
• Ex:
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main()
{
char str[100];
cout<<"Enter String: ";
cin>>str;
By Hansa Halai
int len=strlen(str);
fstream file;
cout<<"nOpen file and store string in it..";
file.open("TEXT",ios::in | ios::out);
for(int i=0;i<len;i++)
{
file.put(str[i]);
}
file.seekg(0);
char ch;
cout<<"nReading the file content..";
while(file){
file.get(ch);
cout<<ch<<"n";
}
return 0;
}
By Hansa Halai
 write() and read() functions:
• The function write() and read() handle data in binary form.
• This means that the values are stored in the disk file in
the same format in which they are stored in the internal
memory.
• The binary format is more accurate for storing the
numbers as they are stored in the exact internal
representation.
• The binary input and output function takes the following
form.
infile.read((char *) & V, sizeof(V));
outfile.write((char *) & V, sizeof(V));
By Hansa Halai
file class
object
Variable name
 These functions takes two arguments, the first is the address of
variable V and the second is the length of that variable in byte.
 The address of the variable must be cast to type char*.
 Ex:
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
const char* filename="BINARY";
int main()
{
char C[4]={'A','B','Z','*'};
ofstream outfile;
outfile.open(filename):
By Hansa Halai
outfile.write((char*)&C,sizeof(C));
outfile.close();
for(int i=0;i<4;i++)
C[i]=0;
ifstream infile;
infile.open(filename);
infile.read((char *)&C,sizeof(C));
for(int i=0;i<4;i++)
{
cout<<setw(10)<<C[i];
}
infile.close();
return 0;
}
By Hansa Halai
Filesin c++

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
File handling
File handlingFile handling
File handling
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
file handling c++
file handling c++file handling c++
file handling c++
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
Data file handling in c++
Data file handling in c++Data file handling in c++
Data file handling in c++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
File Pointers
File PointersFile Pointers
File Pointers
 
Files in c++
Files in c++Files in c++
Files in c++
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
C++ files and streams
C++ files and streamsC++ files and streams
C++ files and streams
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 

Ähnlich wie Filesin c++

Ähnlich wie Filesin c++ (20)

File handling
File handlingFile handling
File handling
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSFILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
File Handling in C
File Handling in CFile Handling in C
File Handling in C
 
Data file handling
Data file handlingData file handling
Data file handling
 
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.2 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.2 pointer, structure ,union and intro to file handling
 
File Handling as 08032021 (1).ppt
File Handling as 08032021 (1).pptFile Handling as 08032021 (1).ppt
File Handling as 08032021 (1).ppt
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
Data file operations in C++ Base
Data file operations in C++ BaseData file operations in C++ Base
Data file operations in C++ Base
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
Python file handlings
Python file handlingsPython file handlings
Python file handlings
 

Kürzlich hochgeladen

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Kürzlich hochgeladen (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

Filesin c++

  • 1. WORKING WITH FILE By Hansa Halai
  • 2.  Many real life problems handle large volume of data and in such situation we need to use some devices such as floppy disk or hard disk to store data.  The data is stored in these devices using the concept of file.  A File is a collection of related data stored in a particular area on the disk.  Program can be designed to perform the read and write operations on these files.  The program can be involves either or both kind of data communications: a. Data transfer between the console unit and the program. b. Data transfer between the program and the disk file. By Hansa Halai
  • 3.  The I/O System of c++ handles the file operations which is very much similar to the console input and output operation.  It uses file stream as an interface between the program and the files.  The stream that supplies data to program is known as input stream.  The stream that receives data from the program is known as output stream.  In other word, the input stream extracts (or read) data from file and the output stream insert (or write) data to file. By Hansa Halai
  • 5. CLASSES FOR FILE STREAM OPERATION: There are three file I/O classes used for read/write operations:  ifstream: can be used to read operations.  ofstream: can be used to write operations.  fstream: can be used for both read and write operations.  fstreambase: serves as base for fstream, ofstream, ifstream. By Hansa Halai
  • 7. OPENING AND CLOSING FILE:  If we want to use a disk file, we need to decide the following things about the file and its intended use: 1. Suitable name for the file. 2. Data type and structure. 3. Purpose. 4. Opening method.  For opening, 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 contain in the header file fstream.  A file can be opened in two ways: 1. Using the constructor function of the class. 2. Using the method function open() of the class. By Hansa Halai
  • 8. The first method is useful when we use only one file in the stream. The second method is used when we want to manage multiple file using one stream.  Opening file using constructor: As we know that a constructor is used to initialize an object while it is being created. here, a file name is used to initialize the file stream object. This involves following steps: 1. Create a file stream object to manage the stream using the appropriate class. That is to say, the class ofstream is used to create the output stream and ifstream to create the input stream. 2. Initialize the file object with the desired filename. For Ex: ofstream outfile(“file1”); By Hansa Halai
  • 10. EXAMPLE: #include<iostream> #include<fstream> using namespace std; int main() { ofstream outf("ITEM"); //connect item file to outf cout<<"Enter Item name: "; char name[10]; cin>>name; outf<<name<<"n"; //write in file ITEM cout<<"Enter Item cost: "; float price; cin>>price; outf<<price<<"n"; By Hansa Halai
  • 11. outf.close(); ifstream inf("ITEM"); inf>>name; // read name from file inf>>price; cout<<"n"; cout<<"Item Name: "<<name<<"n"; cout<<"Item Price: "<<price<<"n"; inf.close(); return 0; } By Hansa Halai Read data from file. The created file is stored in a place where the program is saved.
  • 12. OPENING FILE USING OPEN() METHOD: The open() function is used to open multiple files that use the same stream object.  Syntax: file_stream_class stream_object; stream_object.open(“filename”);  Ex: ofstream ofile; ofile.open(“file1”); … … ofile.close(); ofile.open(“file2”); … … ofile.close(); By Hansa Halai
  • 13.  Note that the first file is closed before the second file is open. This is necessary because a stream can be connected to only one file at a time.  Example: #include<iostream> #include<fstream> using namespace std; int main() { ofstream file1_out; file1_out.open("Country"); file1_out<<"India"<<endl; file1_out<<"UK"<<endl; file1_out<<"USA"<<endl; file1_out.close(); By Hansa Halai
  • 14. file1_out.open("capital"); file1_out<<"Delhi"<<endl; file1_out<<"London"<<endl; file1_out<<"Washington"<<endl; file1_out.close(); const int n=80; char line[n]; ifstream file1_in; file1_in.open("Country"); cout<<"Content of the country file.. n“; while(file1_in) { file1_in.getline(line,n); cout<<"n"; cout<<line; } By Hansa Halai
  • 15. file1_in.close(); file1_in.open("capital"); cout<<"nContent of the capital file..n "; while(file1_in) { file1_in.getline(line,n); cout<<"n"; cout<<line; } file1_in.close(); return 0; } o Output: By Hansa Halai
  • 16. READING FROM TWO FILES SIMULTANEOUSLY:  Example: #include<iostream> #include<fstream> #include<stdlib.h> using namespace std; int main() { const int size = 50; char line[size]; ifstream fin1,fin2; fin1.open("country"); fin2.open("capital"); By Hansa Halai
  • 17. for(int i=1;i<=3;i++) { if(fin1.eof()!=0) { cout<<"Exit from country file..n"; exit(1); } fin1.getline(line,size); cout<<"nCapital of "<<line<<endl; if(fin2.eof()!=0) { cout<<"nExit from capital file.."; exit(1); } fin2.getline(line,size); cout<<" "<<line<<"n"; } return 0; } By Hansa Halai
  • 18. DETECTING END-OF-FILE:  Detection of the end-of-file condition is necessary for preventing any further attempt to read data from the file. We can achieve this by using following two statement:  1) while (file_stream_object) Ex: while(fin) The while loop terminates when fin object returns a value of zero or reaching at the end-of-file. 2) if(fin.eof()!=0) { exit(1); }  The eof() is a member function of ios class. It returns a non- zero value if the end-of-file condition encountered. Therefore , the statement terminates the program on reaching the end of file. By Hansa Halai
  • 19. FILE MODES:  We have used ifstream and ofstream constructor and open() method to create a new file or open a existing file. By Hansa Halai File Type Default Open Mode ofstream The file is opened for output only. (Information may be written to the file, but not read from the file.) If the file does not exist, it is created. If the file already exists, its contents are deleted (the file is truncated). ifstream The file is opened for input only. (Information may be read from the file, but not written to it.) The file’s contents will be read from its beginning. If the file does not exist, the open function fails.
  • 20.  In both these methods, we used only one argument list that was file name.  open() can also take two arguments, the second one specifying the file mode.  syntax: stream_object.open(“file_name”,mode);  Ex: fout.open(“student”,ios::out) ;  The prototype of these class member functions contains default value for second argument and therefore they use the default value in absence of the actual values. The default values as follows: ios::in – For ifstream function meaning open for reading only. ios::out – For ofstream function meaning open for writing only. By Hansa Halai
  • 21. By Hansa Halai File Mode Flag Meaning ios::app Append mode. If the file already exists, its contents are preserved and all output is written to the end of the file. By default, this flag causes the file to be created if it does not exist. ios::ate If the file already exists, the program goes directly to the end of it. Output may be written anywhere in the file. ios::binary Binary mode. When a file is opened in binary mode, information is written to or read from it in pure binary format. (The default mode is text.) ios::in Input mode. Information will be read from the file. If the file does not exist, it will not be created and the open function will fail.
  • 22. By Hansa Halai File Mode Flag Meaning ios::nocreate If the file does not already exist, this flag will cause the open function to fail. (The file will not be created.) ios::noreplace If the file already exists, this flag will cause the open function to fail. (The existing file will not be opened.) ios::out Output mode. Information will be written to the file. By default, the file’s contents will be deleted if it already exists. ios::trunc If the file already exists, its contents will be deleted (truncated). This is the default mode used by ios::out.
  • 23. FILE POINTER AND THEIR MANIPULATIONS:  Each file has two associated pointer known as the file pointers. one of them is called input pointer or get pointer and other is called the output pointer or put pointer.  The input pointer is used for reading the content of given file location and output pointer is used for writing to a given file location.  Each time an input and output operation takes place, the appropriate pointer is automatically advanced. By Hansa Halai
  • 24.  Default action: When we open file in read only mode the input pointer automatically set at the beginning so that we can read the file from start. When we open file in write only mode the input pointer the existing contents are deleted and the output pointer is set at the beginning. This enables us to write the file from start. By Hansa Halai
  • 25. By Hansa Halai In case we want to open an existing file to add more data, the file is opened in “append” mode, which is move file pointer at the end of file.
  • 26.  Functions for manipulation of file pointer:  As we shown file pointer takes place automatically by default. But how do we move a file pointer to any other desired location. This is possible only if we can take control of movement of file pointers ourselves.  The File stream classes support the following function to manage such situation:  seekg(): Move get pointer to specific location.(read)  seekp():Move put pointer to specific location.(write)  tellg(): Gives the current position of the get pointer.  tellp():Gives the current position of the put pointer. By Hansa Halai
  • 27.  Example: #include <iostream> #include <fstream> using namespace std; int main() { fstream dataFile("sentence.txt", ios::out); char ch; cout << "Type a sentence and be sure to end it with a "; cout << "period.n"; while (1) { cin.get(ch); dataFile.put(ch); if (ch == '.') break; } By Hansa Halai
  • 28. dataFile.close(); dataFile.open("sentence.txt", ios::in); char c; dataFile.seekg(3L, ios::beg); dataFile.get(c); cout << "nByte 3 from beginning: " << c << endl; dataFile.seekg(-5L, ios::end); dataFile.get(c); cout << "nByte 5 from end: " << c << endl; dataFile.close(); } By Hansa Halai
  • 29.  Example-2: #include<iostream> #include<fstream> using namespace std; int main(){ ofstream outf("test"); cout<<"Enter String: "; char str[20]; cin>>str; outf<<str; cout<<"n"; int p=outf.tellp(); cout<<"size of file:"<<p; outf.close(); By Hansa Halai Represent the number of bytes in the file
  • 30. ifstream inf; inf.open("test"); cout<<"n"; cout<<"nString is: "<<str<<"n"; inf>>str; inf.close(); return 0; } By Hansa Halai
  • 31.  Specifying the offset: We have just seen how to move a file pointer to a desired location using the seek function. The argument to these functions represents the absolute position in the file.  Seekg() and seekp() can also be used with two arguments as follows: seekg(offset,refposition); seekp(offset,refposition); By Hansa Halai
  • 32.  The parameter offset represent 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 Ex: (In File pointer and their Manipulations Ex-1) By Hansa Halai
  • 33. SEQUENTIAL INPUT AND OUTPUT OPERATIONS:  The file stream classes support a number of member functions for performing the input and output operation on file.  One pair of the function get() and put() are designed for handling a single character at a time.  Another pair of functions write() and read() are designed to write and read block of binary data. By Hansa Halai
  • 34.  put() and get() function: • The function put() writes a single character to associated stream. • The function get() reads a single character from associated stream . • Ex: #include<iostream> #include<fstream> #include<string.h> using namespace std; int main() { char str[100]; cout<<"Enter String: "; cin>>str; By Hansa Halai
  • 35. int len=strlen(str); fstream file; cout<<"nOpen file and store string in it.."; file.open("TEXT",ios::in | ios::out); for(int i=0;i<len;i++) { file.put(str[i]); } file.seekg(0); char ch; cout<<"nReading the file content.."; while(file){ file.get(ch); cout<<ch<<"n"; } return 0; } By Hansa Halai
  • 36.  write() and read() functions: • The function write() and read() handle data in binary form. • This means that the values are stored in the disk file in the same format in which they are stored in the internal memory. • The binary format is more accurate for storing the numbers as they are stored in the exact internal representation. • The binary input and output function takes the following form. infile.read((char *) & V, sizeof(V)); outfile.write((char *) & V, sizeof(V)); By Hansa Halai file class object Variable name
  • 37.  These functions takes two arguments, the first is the address of variable V and the second is the length of that variable in byte.  The address of the variable must be cast to type char*.  Ex: #include<iostream> #include<fstream> #include<iomanip> using namespace std; const char* filename="BINARY"; int main() { char C[4]={'A','B','Z','*'}; ofstream outfile; outfile.open(filename): By Hansa Halai
  • 38. outfile.write((char*)&C,sizeof(C)); outfile.close(); for(int i=0;i<4;i++) C[i]=0; ifstream infile; infile.open(filename); infile.read((char *)&C,sizeof(C)); for(int i=0;i<4;i++) { cout<<setw(10)<<C[i]; } infile.close(); return 0; } By Hansa Halai