SlideShare ist ein Scribd-Unternehmen logo
1 von 37
DISCOVER . LEARN . EMPOWER
Topic: File handling
INSTITUTE - UIE
DEPARTMENT- ACADEMIC UNIT-2
Bachelor of Engineering (Computer Science & Engineering)
Subject Name: Object Oriented Programming using C++
Code:20CST151
Unit-3
Object Oriented
Programming
using C++
Course Objectives
2
• To enable the students to understand various stages and constructs
of C++ programming language and relate them to engineering
programming problems.
• To improve their ability to analyze and address variety of problems in
programming domains.
3
CO
Number
Title Level
CO1 Provide the environment that allows students to
understand object-oriented programming Concepts.
Understand
CO2 Demonstrate basic experimental skills for differentiating
between object-oriented and procedural programming
paradigms and the advantages of object-oriented
programs.
Remember
CO3 Demonstrate their coding skill on complex programming
concepts and use it for generating solutions for
engineering and mathematical problems.
Understand
CO4 Develop skills to understand the application of classes,
objects, constructors, destructors, inheritance, operator
overloading and polymorphism, pointers, virtual
functions, exception handling, file operations and
handling.
Understand
Course Outcomes
Scheme of Evaluation
4
Sr.
No.
Type of Assessment
Task
Weightage of actual
conduct
Frequency of Task Final Weightage in Internal
Assessment (Prorated
Marks)
Remarks
1. Assignment* 10 marks of
each assignment
One Per Unit 10 marks As applicable to
course types depicted
above.
2. Time Bound
Surprise
Test
12 marks for each
test
One per Unit 4 marks As applicable to
course types
depicted above.
3. Quiz 4 marks of each quiz 2 per Unit 4marks As applicable to
course types
depicted above.
4. Mid-Semester Test** 20 marks for one
MST.
2 per semester 20 marks As applicable to
course types
depicted above.
5. Presentation*** Non Graded: Engagement
Task
Only for Self Study
MNGCourses.
6. Homework NA One per lecture topic
(of 2
questions)
Non-Graded: Engagement
Task
As applicable to
course types
depicted above.
7. Discussion Forum NA One per
Chapter
Non Graded: Engagement
Task
As applicable to
course types depicted
above.
8. Attendance and
Engagement Score
on BB
NA NA 2 marks
• Introduction of file
handling
• File operations and
file modes
• Examples
5
CONTENTS
What is a File?
• A file is a collection of bytes stored on a secondary storage device,
which is generally a disk of some kind.
• The collection of bytes may be interpreted, for example,
characters, words, lines, paragraphs from a text document;
fields and records belonging to a database;
Or pixels from a graphical image.
• We use files to store data which can be processed by our programs.
• Not only data but our programs are also stored in files
6
NEED FOR DATAFILES
• Many real life problems requires handling of large amount of data.
• Earlier we used arrays to store bulk data.
• The problem with the arrays is that arrays are stored in RAM.
• The data stored in arrays is retained as long as the program is
running. Once the program is over the data stored in the arrays is
also lost.
• To store the data permanently we need files.
• Note: Files are required to save our data (on a secondary storage
device) for future use, as RAM is not able to hold our data
permanently.
7
INPUT/OUTPUT IN C++ STREAMS
• The input/output system of C++ handles file I/O operations in the
same way it handles console I/O operations.
• It uses file stream as an interface between programs and files.
• A stream is defined as the flow of data.
• Different kinds of stream are used to represent different kinds of data
flow.
• Output stream: The stream which controls the flow of data from the
program to file is called output stream.
• Input stream: The stream which controls the flow of data from the
file to the program is called input stream.
8
INPUT/OUTPUT IN C++ STREAMS
9
INPUT/OUTPUT IN C++ STREAMS
• Each stream is associated with a particular
• class which contains definitions and methods for dealing with that
particular kind of data
• These include fstream, ifstream and ofstream. These classes are
defined in the header file fstream.h. Therefore it is necessary to
include this header file while writing file programs.
• The classes contained in fstream.h are derived from iostream.h. Thus
it is not necessary to include iostream.h in our program, if we are
using the header file fstream.h in it.
10
INPUT/OUTPUT IN C++ STREAMS
11
INPUT/OUTPUT IN C++ STREAMS CONTD…
• The ifstream class contains open() function with default input mode
and inherits the functions get(), getline(), read(), seekg() and tellg().
• The ofstream class contains open() function with default output
mode and inherits functions put(), write(), seekp() and tellp() from
ostream.
• The fstream class contains open() function with default input/output
mode and inherits all I/O functions from iostream.h.
12
TYPES OF DATA FILES
There are two types of data files in C++: Text files and Binary files
• Text files store the information in ASCII characters. Each line of text in
text files is terminated by a special character called EOL. In text files
some internal translations take place while storing data.
• Binary files store information in binary format. There is no EOL
character in binary files and no character translation takes place in
binary files.
13
DIFFERENCE BETWEEN TEXT FILES
AND BINARY FILES
14
DIFFERENCE BETWEEN TEXT FILES
AND BINARY FILES CONTD…
15
C++ provides us with the following operations
in File Handling:
• Creating a file: open()
• Reading data: read()
• Writing new data: write()
• Closing a file: close()
16
OPENING A FILE
Generally, the first operation performed on an object of one of these classes is to
associate it to a real file. This procedure is known to open a file.
We can open a file using any one of the following methods:
• 1. First is by passing the file name in constructor at the time of object creation.
• 2. Second is using the open() function.
To open a file, use open() function
Syntax
void open(const char* file_name,ios::openmode mode);
Here, the first argument of the open function defines the name and format of the
file with the address of the file.
The second argument represents the mode in which the file has to be opened.
17
OPENING A FILE- OPENING MODES
The following modes are used as per the requirements
Example:
fstream new_file;
new_file.open(“newfile.txt”, ios::out);
18
Default Open Modes :
ifstream ios::in
ofstream ios::out
fstream ios::in | ios::out
We can combine the different modes
using or symbol | .
Example of opening/creating a file using the
open() function
19
Example of opening/creating a file using the
open() function
20
Program Explanation
• In the above example we first create an object to class fstream and
name it ‘new_file’.
• Then we apply the open() function on our ‘new_file’ object.
• We give the name ‘new_file’ to the new file we wish to create and we
set the mode to ‘out’ which allows us to write in our file.
• We use a ‘if’ statement to find if the file already exists or not if it does
exist then it will going to print “File creation failed” or it will create a
new file and print “New file created”.
21
Example 2: opening/creating a file using the
open() function
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream my_file;
my_file.open("my_file", ios::out);
if (!my_file) {
cout << "File not created!";
}
else {
cout << "File created successfully!";
my_file.close();
}
return 0;} 22
Output
23
Screenshot of the code:
24
Explanation of the Program
25
Close a File
It is simply done with the help of close() function.
Syntax: File Pointer.close()
26
Close a File
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file.txt",ios::out);
new_file.close();
return 0;
}
Output:
The file gets closed.
27
Applications
• Files are used to store data in a storage device permanently.
File handling provides a mechanism to store the output of a
program in a file and to perform various operations on it.
• Reusability: It helps in preserving the data or information generated
after running the program.
• Large storage capacity: Using files, you need not worry about the
problem of storing data in bulk.
28
29
Summary
In this lecture we have
discussed about File Handling.
We have discussed about File
Operations and File modes
Discussed about examples of
Opening and Closing a file
Frequently Asked question
Q1:It is not possible to combine two or more file opening mode in open ()
method.
A. TRUE
B. FALSE
C. May Be
D. Can't Say
Ans: B
30
Q2: Which of the following methods can be used to open a file in file
handling?
A. Using Open ( )
B. Constructor method
C. Destructor method
D. Both A and B
Ans: D
31
32
Q3: Which is correct syntax ?
A. myfile:open ("example.bin", ios::out);
B. myfile.open ("example.bin", ios::out);
C. myfile::open ("example.bin", ios::out);
D. myfile.open ("example.bin", ios:out);
Ans: B
Assessment Questions:
33
1. ios::trunc is used for ?
A. If the file is opened for output operations and it already existed, no action is taken.
B. If the file is opened for output operations and it already existed, then a new copy is created.
C. If the file is opened for output operations and it already existed, its previous content is deleted
and replaced by the new one.
D. None of the above
2. Which of the following true about FILE *fp
A. FILE is a structure and fp is a pointer to the structure of FILE type
B. FILE is a buffered stream
C. FILE is a keyword in C for representing files and fp is a variable of FILE type
D. FILE is a stream
34
3 . Which of the following is used to create an output stream?
a) ofstream
b) ifstream
c) iostream
d) fsstream
4. Which header file is required to use file I/O operations?
a) <ifstream>
b) <ostream>
c) <fstream>
d) <iostream>
5. Which of the following is not used as a file opening mode?
a) ios::trunc
b) ios::binary
c) ios::in
d) ios::ate
Discussion forum.
35
TRY THIS!!
Given that a binary file “student.dat” is already loaded in
the memory of the computer with the record of 100
students, the task is to read the Kth record and perform
some operations.
REFERENCES
Reference Books
[1] Programming in C by Reema Thareja.
[2] Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.
[3] Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender
Chhabra, Tata McGraw Hill.
[4] The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson
education.
Websites:
 https://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm
 https://www.edureka.co/blog/file-handling-in-cpp/
 https://www.geeksforgeeks.org/file-handling-c-classes/
YouTube Links:
What is File Handling?
https://spoken-
tutorial.org/watch/C+and+Cpp/File+Handling+In+C/English/
36
THANK YOU

Weitere ähnliche Inhalte

Ähnlich wie File handling.pptx

ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
aquacare2008
 
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
 

Ähnlich wie File handling.pptx (20)

File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
File management in C++
File management in C++File management in C++
File management in C++
 
File Handling and Preprocessor Directives
File Handling and Preprocessor DirectivesFile Handling and Preprocessor Directives
File Handling and Preprocessor Directives
 
null.pptx
null.pptxnull.pptx
null.pptx
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
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)
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
ExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdfExplanationThe files into which we are writing the date area called.pdf
ExplanationThe files into which we are writing the date area called.pdf
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
File handling
File handlingFile handling
File handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
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
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
Python file handling
Python file handlingPython file handling
Python file handling
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 

Kürzlich hochgeladen

Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 

Kürzlich hochgeladen (20)

FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf22-prompt engineering noted slide shown.pdf
22-prompt engineering noted slide shown.pdf
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 

File handling.pptx

  • 1. DISCOVER . LEARN . EMPOWER Topic: File handling INSTITUTE - UIE DEPARTMENT- ACADEMIC UNIT-2 Bachelor of Engineering (Computer Science & Engineering) Subject Name: Object Oriented Programming using C++ Code:20CST151 Unit-3
  • 2. Object Oriented Programming using C++ Course Objectives 2 • To enable the students to understand various stages and constructs of C++ programming language and relate them to engineering programming problems. • To improve their ability to analyze and address variety of problems in programming domains.
  • 3. 3 CO Number Title Level CO1 Provide the environment that allows students to understand object-oriented programming Concepts. Understand CO2 Demonstrate basic experimental skills for differentiating between object-oriented and procedural programming paradigms and the advantages of object-oriented programs. Remember CO3 Demonstrate their coding skill on complex programming concepts and use it for generating solutions for engineering and mathematical problems. Understand CO4 Develop skills to understand the application of classes, objects, constructors, destructors, inheritance, operator overloading and polymorphism, pointers, virtual functions, exception handling, file operations and handling. Understand Course Outcomes
  • 4. Scheme of Evaluation 4 Sr. No. Type of Assessment Task Weightage of actual conduct Frequency of Task Final Weightage in Internal Assessment (Prorated Marks) Remarks 1. Assignment* 10 marks of each assignment One Per Unit 10 marks As applicable to course types depicted above. 2. Time Bound Surprise Test 12 marks for each test One per Unit 4 marks As applicable to course types depicted above. 3. Quiz 4 marks of each quiz 2 per Unit 4marks As applicable to course types depicted above. 4. Mid-Semester Test** 20 marks for one MST. 2 per semester 20 marks As applicable to course types depicted above. 5. Presentation*** Non Graded: Engagement Task Only for Self Study MNGCourses. 6. Homework NA One per lecture topic (of 2 questions) Non-Graded: Engagement Task As applicable to course types depicted above. 7. Discussion Forum NA One per Chapter Non Graded: Engagement Task As applicable to course types depicted above. 8. Attendance and Engagement Score on BB NA NA 2 marks
  • 5. • Introduction of file handling • File operations and file modes • Examples 5 CONTENTS
  • 6. What is a File? • A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. • The collection of bytes may be interpreted, for example, characters, words, lines, paragraphs from a text document; fields and records belonging to a database; Or pixels from a graphical image. • We use files to store data which can be processed by our programs. • Not only data but our programs are also stored in files 6
  • 7. NEED FOR DATAFILES • Many real life problems requires handling of large amount of data. • Earlier we used arrays to store bulk data. • The problem with the arrays is that arrays are stored in RAM. • The data stored in arrays is retained as long as the program is running. Once the program is over the data stored in the arrays is also lost. • To store the data permanently we need files. • Note: Files are required to save our data (on a secondary storage device) for future use, as RAM is not able to hold our data permanently. 7
  • 8. INPUT/OUTPUT IN C++ STREAMS • The input/output system of C++ handles file I/O operations in the same way it handles console I/O operations. • It uses file stream as an interface between programs and files. • A stream is defined as the flow of data. • Different kinds of stream are used to represent different kinds of data flow. • Output stream: The stream which controls the flow of data from the program to file is called output stream. • Input stream: The stream which controls the flow of data from the file to the program is called input stream. 8
  • 10. INPUT/OUTPUT IN C++ STREAMS • Each stream is associated with a particular • class which contains definitions and methods for dealing with that particular kind of data • These include fstream, ifstream and ofstream. These classes are defined in the header file fstream.h. Therefore it is necessary to include this header file while writing file programs. • The classes contained in fstream.h are derived from iostream.h. Thus it is not necessary to include iostream.h in our program, if we are using the header file fstream.h in it. 10
  • 11. INPUT/OUTPUT IN C++ STREAMS 11
  • 12. INPUT/OUTPUT IN C++ STREAMS CONTD… • The ifstream class contains open() function with default input mode and inherits the functions get(), getline(), read(), seekg() and tellg(). • The ofstream class contains open() function with default output mode and inherits functions put(), write(), seekp() and tellp() from ostream. • The fstream class contains open() function with default input/output mode and inherits all I/O functions from iostream.h. 12
  • 13. TYPES OF DATA FILES There are two types of data files in C++: Text files and Binary files • Text files store the information in ASCII characters. Each line of text in text files is terminated by a special character called EOL. In text files some internal translations take place while storing data. • Binary files store information in binary format. There is no EOL character in binary files and no character translation takes place in binary files. 13
  • 14. DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES 14
  • 15. DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES CONTD… 15
  • 16. C++ provides us with the following operations in File Handling: • Creating a file: open() • Reading data: read() • Writing new data: write() • Closing a file: close() 16
  • 17. OPENING A FILE Generally, the first operation performed on an object of one of these classes is to associate it to a real file. This procedure is known to open a file. We can open a file using any one of the following methods: • 1. First is by passing the file name in constructor at the time of object creation. • 2. Second is using the open() function. To open a file, use open() function Syntax void open(const char* file_name,ios::openmode mode); Here, the first argument of the open function defines the name and format of the file with the address of the file. The second argument represents the mode in which the file has to be opened. 17
  • 18. OPENING A FILE- OPENING MODES The following modes are used as per the requirements Example: fstream new_file; new_file.open(“newfile.txt”, ios::out); 18 Default Open Modes : ifstream ios::in ofstream ios::out fstream ios::in | ios::out We can combine the different modes using or symbol | .
  • 19. Example of opening/creating a file using the open() function 19
  • 20. Example of opening/creating a file using the open() function 20
  • 21. Program Explanation • In the above example we first create an object to class fstream and name it ‘new_file’. • Then we apply the open() function on our ‘new_file’ object. • We give the name ‘new_file’ to the new file we wish to create and we set the mode to ‘out’ which allows us to write in our file. • We use a ‘if’ statement to find if the file already exists or not if it does exist then it will going to print “File creation failed” or it will create a new file and print “New file created”. 21
  • 22. Example 2: opening/creating a file using the open() function #include <iostream> #include <fstream> using namespace std; int main() { fstream my_file; my_file.open("my_file", ios::out); if (!my_file) { cout << "File not created!"; } else { cout << "File created successfully!"; my_file.close(); } return 0;} 22
  • 24. Screenshot of the code: 24
  • 25. Explanation of the Program 25
  • 26. Close a File It is simply done with the help of close() function. Syntax: File Pointer.close() 26
  • 27. Close a File #include <iostream> #include <fstream> using namespace std; int main() { fstream new_file; new_file.open("new_file.txt",ios::out); new_file.close(); return 0; } Output: The file gets closed. 27
  • 28. Applications • Files are used to store data in a storage device permanently. File handling provides a mechanism to store the output of a program in a file and to perform various operations on it. • Reusability: It helps in preserving the data or information generated after running the program. • Large storage capacity: Using files, you need not worry about the problem of storing data in bulk. 28
  • 29. 29 Summary In this lecture we have discussed about File Handling. We have discussed about File Operations and File modes Discussed about examples of Opening and Closing a file
  • 30. Frequently Asked question Q1:It is not possible to combine two or more file opening mode in open () method. A. TRUE B. FALSE C. May Be D. Can't Say Ans: B 30
  • 31. Q2: Which of the following methods can be used to open a file in file handling? A. Using Open ( ) B. Constructor method C. Destructor method D. Both A and B Ans: D 31
  • 32. 32 Q3: Which is correct syntax ? A. myfile:open ("example.bin", ios::out); B. myfile.open ("example.bin", ios::out); C. myfile::open ("example.bin", ios::out); D. myfile.open ("example.bin", ios:out); Ans: B
  • 33. Assessment Questions: 33 1. ios::trunc is used for ? A. If the file is opened for output operations and it already existed, no action is taken. B. If the file is opened for output operations and it already existed, then a new copy is created. C. If the file is opened for output operations and it already existed, its previous content is deleted and replaced by the new one. D. None of the above 2. Which of the following true about FILE *fp A. FILE is a structure and fp is a pointer to the structure of FILE type B. FILE is a buffered stream C. FILE is a keyword in C for representing files and fp is a variable of FILE type D. FILE is a stream
  • 34. 34 3 . Which of the following is used to create an output stream? a) ofstream b) ifstream c) iostream d) fsstream 4. Which header file is required to use file I/O operations? a) <ifstream> b) <ostream> c) <fstream> d) <iostream> 5. Which of the following is not used as a file opening mode? a) ios::trunc b) ios::binary c) ios::in d) ios::ate
  • 35. Discussion forum. 35 TRY THIS!! Given that a binary file “student.dat” is already loaded in the memory of the computer with the record of 100 students, the task is to read the Kth record and perform some operations.
  • 36. REFERENCES Reference Books [1] Programming in C by Reema Thareja. [2] Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill. [3] Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender Chhabra, Tata McGraw Hill. [4] The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson education. Websites:  https://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm  https://www.edureka.co/blog/file-handling-in-cpp/  https://www.geeksforgeeks.org/file-handling-c-classes/ YouTube Links: What is File Handling? https://spoken- tutorial.org/watch/C+and+Cpp/File+Handling+In+C/English/ 36

Hinweis der Redaktion

  1. Computer in the diagram is 3rd generation computer. The period of third generation was from 1965-1971. The computers of third generation used Integrated Circuits (ICs) in place of transistors. A single IC has many transistors, resistors, and capacitors along with the associated circuitry. The main features of third generation are − IC used More reliable in comparison to previous two generations Smaller size Generated less heat Faster Lesser maintenance Costly AC required Consumed lesser electricity Supported high-level language