Ch6 - File Streaming PF supporting material
Ch6 - File Streaming PF supporting material
Lecture 39-40
2
C++ Files and Streams
4
Writing to a File
• Write information to a file from your program, using stream
insertion operator (<<) just as you use that operator to output
information to the screen.
5
Reading from a File
• 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.
6
7
Closing a File
• When a C++ program terminates,
– automatically closes flushes all the streams,
– release all the allocated memory and
– close all the opened files.
– void close();
8
Read & Write Example
#include<constream.h>
#include<fstream.h>
void main()
{ clrscr();
char data[100];
ofstream outfile;
outfile.open("test1.dat");
cout<<"Writing Data ";
cout<<"\nEnter your name : ";
cin.getline(data,100);
cout<<data<<endl; //Print data on console
outfile<<data<<endl; //print/write data on file
cout<<"\n\n Data written successfully\n\n";
outfile.close(); 9
Read & Write Example
ifstream infile; //infile instance created
infile.open("test1.dat");
cout<<"\n Reading data from the file \n";
infile>>data;
cout<<"Write data on the screen \n";
cout<<data;
getch();
10
}
Assignment
Create a file with your own name using filing.
Write your name, roll number and cnic number.
Then read data from that file on console.
11