SlideShare une entreprise Scribd logo
1  sur  60
0
 Outline:
◦ concept of byte streams
◦ File access methods
◦ Opening and closing files
◦ Reading from files
◦ Write to files
 When a program runs, the data is in the memory, but when it ends or
the computer shuts down, it gets lost. To keep data permanently, we
need to write it in a file.
 A file is a collection of information, usually stored on a computer’s
disk. Information can be saved to files and then later reused.
 All files are assigned a name that is used for identification purposes
by the operating system and the user.
 We use file handling to store data permanently.
1
 Text file: it is a file that stores information in ASCII
characters. in a text file each line of text is terminated with a
special character known as EOL(End of Line) character or
delimiter character.
 Binary file: it is a file that contains information in the same
format as it is held in memory. in a binary file, no delimiters
are used for a line.
 Binary files are faster and easier for programs to read and
write.
2
 Sequential access: with this type of file access one must read
the data in order, much like with a tape whether the data is
really stored on tape or not.
 Random access: this type of file access lets you jump to any
location in the file. Write data to file
3
 A stream is a general term used to name the flow of
data.
 streams act as an interface between files and programs.
4
 File input stream: reads data from disk file to the program.
 File output stream: writes data to the disk from the program.
 The I/O system of C++ contains:
5
ofstream It used to create files and write on files.
ifstream It used to read from files.
fsream Supports both ifstream and ofstream operations.
Step1:Declare a file name variable
Step 2: Associate the file name variable with the disk file name.
Step3:Open the file
Step4:Use the file
Step5:Close the file
6
functions operation
open() To create a file.
close() To close an exsisting file.
get() Read a single character from file
put() Write a single character in file
read() Read data from file
write() Write data into file.
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
I. Declare a file name variable
◦ ifstream input_filename_var; // input file
◦ ofstream output_filename_var; // output file
II. Associate the file name variable with the
disk file name and open it.
◦ input_filename_var.open(“pathname/filename”);
◦ output_filename_var.open(“pathname/filename”);
53
 A file must be opened before you can read from it or write to it.
 Either ofstream or fstream object may be used to open a file for writing.
ifstream object is used to open a file for reading purpose only.
 The following are the different modes in which we can open a file.
54
ios::in opens a text file for reading.
ios::out opens a text file for writing.
ios::app
opens a text file for appending. (appending means to add text
at the end).
ios::ate
opens a file for output and move the read/write control to the
end of the file.
ios::trunc truncates the content before opening a file, if file exists.
ifstream input_filename_var(pathname/filename, ios::in);
ofstream input_filename_var(pathname/filename, ios::out);
Writing to a File:
 You write information to a file from your program using stream insertion operator
(<<) just as you use that operator to output information to the screen.
 The only difference is that you use an ofstream or fstream object instead of
the cout object.
◦ ofstream ofile1;
◦ ofile1 << x << y; // x and y are integers
◦ ofile2 << ch; // ch is a char
◦ ofile3 << “Hi there!” << endl; // literal string
◦ ofile4 << str; // str is a char*
55
 You read information from a file into your program using the stream
extraction operator (>>) just as you use that operator to input
information from the keyboard.
 The only difference is that you use an ifstream or fstream object
instead of the cin object.
◦ ifstream infile1;
◦ ifile1 >> x >> y; // x and y are integers
◦ ifile2 >> ch; // ch is a char
◦ ch = ifile3.get(); // ch is a char
◦ ifile4.getline(buffer, buffer_size) // buffer is char*
56
Reading from a File
IV. Close the file
 When a C++ program terminates it automatically flushes all the
streams, release all the allocated memory and close all the opened
files. But it is always a good practice that a programmer should
close all the opened files before program termination.
◦ input_filename_var.close();
◦ output_filename_var.close();
57
58
59
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and
display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}

Contenu connexe

Similaire à Chapter4.pptx

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
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 handlingRai University
 
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++ ProgrammingChereLemma2
 
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 handlingRai University
 
File Handling in c++
File Handling in c++File Handling in c++
File Handling in c++SoniKirtan
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
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 referenceanuvayalil5525
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxAssadLeo1
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 

Similaire à Chapter4.pptx (20)

VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
File handling
File handlingFile handling
File handling
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
 
File handling
File handlingFile handling
File handling
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
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
 
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
 
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
 
Data file handling
Data file handlingData file handling
Data file handling
 
file_c.pdf
file_c.pdffile_c.pdf
file_c.pdf
 
File Handling in c++
File Handling in c++File Handling in c++
File Handling in c++
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes 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
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
FILES IN C
FILES IN CFILES IN C
FILES IN C
 
INput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptxINput output stream in ccP Full Detail.pptx
INput output stream in ccP Full Detail.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 

Dernier

BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdfKamal Acharya
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
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 Bookingdharasingh5698
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 

Dernier (20)

BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
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
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 

Chapter4.pptx

  • 1. 0  Outline: ◦ concept of byte streams ◦ File access methods ◦ Opening and closing files ◦ Reading from files ◦ Write to files
  • 2.  When a program runs, the data is in the memory, but when it ends or the computer shuts down, it gets lost. To keep data permanently, we need to write it in a file.  A file is a collection of information, usually stored on a computer’s disk. Information can be saved to files and then later reused.  All files are assigned a name that is used for identification purposes by the operating system and the user.  We use file handling to store data permanently. 1
  • 3.  Text file: it is a file that stores information in ASCII characters. in a text file each line of text is terminated with a special character known as EOL(End of Line) character or delimiter character.  Binary file: it is a file that contains information in the same format as it is held in memory. in a binary file, no delimiters are used for a line.  Binary files are faster and easier for programs to read and write. 2
  • 4.  Sequential access: with this type of file access one must read the data in order, much like with a tape whether the data is really stored on tape or not.  Random access: this type of file access lets you jump to any location in the file. Write data to file 3
  • 5.  A stream is a general term used to name the flow of data.  streams act as an interface between files and programs. 4
  • 6.  File input stream: reads data from disk file to the program.  File output stream: writes data to the disk from the program.  The I/O system of C++ contains: 5 ofstream It used to create files and write on files. ifstream It used to read from files. fsream Supports both ifstream and ofstream operations.
  • 7. Step1:Declare a file name variable Step 2: Associate the file name variable with the disk file name. Step3:Open the file Step4:Use the file Step5:Close the file 6
  • 8. functions operation open() To create a file. close() To close an exsisting file. get() Read a single character from file put() Write a single character in file read() Read data from file write() Write data into file. 7
  • 9. 8
  • 10. 9
  • 11. 10
  • 12. 11
  • 13. 12
  • 14. 13
  • 15. 14
  • 16. 15
  • 17. 16
  • 18. 17
  • 19. 18
  • 20. 19
  • 21. 20
  • 22. 21
  • 23. 22
  • 24. 23
  • 25. 24
  • 26. 25
  • 27. 26
  • 28. 27
  • 29. 28
  • 30. 29
  • 31. 30
  • 32. 31
  • 33. 32
  • 34. 33
  • 35. 34
  • 36. 35
  • 37. 36
  • 38. 37
  • 39. 38
  • 40. 39
  • 41. 40
  • 42. 41
  • 43. 42
  • 44. 43
  • 45. 44
  • 46. 45
  • 47. 46
  • 48. 47
  • 49. 48
  • 50. 49
  • 51. 50
  • 52. 51
  • 53. 52
  • 54. I. Declare a file name variable ◦ ifstream input_filename_var; // input file ◦ ofstream output_filename_var; // output file II. Associate the file name variable with the disk file name and open it. ◦ input_filename_var.open(“pathname/filename”); ◦ output_filename_var.open(“pathname/filename”); 53
  • 55.  A file must be opened before you can read from it or write to it.  Either ofstream or fstream object may be used to open a file for writing. ifstream object is used to open a file for reading purpose only.  The following are the different modes in which we can open a file. 54 ios::in opens a text file for reading. ios::out opens a text file for writing. ios::app opens a text file for appending. (appending means to add text at the end). ios::ate opens a file for output and move the read/write control to the end of the file. ios::trunc truncates the content before opening a file, if file exists. ifstream input_filename_var(pathname/filename, ios::in); ofstream input_filename_var(pathname/filename, ios::out);
  • 56. Writing to a File:  You write information to a file from your program using stream insertion operator (<<) just as you use that operator to output information to the screen.  The only difference is that you use an ofstream or fstream object instead of the cout object. ◦ ofstream ofile1; ◦ ofile1 << x << y; // x and y are integers ◦ ofile2 << ch; // ch is a char ◦ ofile3 << “Hi there!” << endl; // literal string ◦ ofile4 << str; // str is a char* 55
  • 57.  You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard.  The only difference is that you use an ifstream or fstream object instead of the cin object. ◦ ifstream infile1; ◦ ifile1 >> x >> y; // x and y are integers ◦ ifile2 >> ch; // ch is a char ◦ ch = ifile3.get(); // ch is a char ◦ ifile4.getline(buffer, buffer_size) // buffer is char* 56 Reading from a File
  • 58. IV. Close the file  When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination. ◦ input_filename_var.close(); ◦ output_filename_var.close(); 57
  • 59. 58
  • 60. 59 #include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // open a file in write mode. ofstream outfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // write inputted data into the file. outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // again write inputted data into the file. outfile << data << endl; // close the opened file. outfile.close(); // open a file in read mode. ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // write the data at the screen. cout << data << endl; // again read the data from the file and display it. infile >> data; cout << data << endl; // close the opened file. infile.close(); return 0; }