Professional Documents
Culture Documents
LECTURE 10
1
Objectives:
2
FILES
record of data
3
FILES
4
FILES
5
FILES & STREAM
6
FILES & STREAMS
7
FILES & STREAMS
8
FILES & STREAMS
• We can use our file streams the same way we use cin and
cout, with the only difference that we have to associate
these streams with physical files.
9
FILES & STREAMS
10
INPUT/OUTPUT FILES
11
INPUT/OUTPUT FILES : Opening a file
12
INPUT/OUTPUT FILES : Opening a file
13
INPUT/OUTPUT FILES : Opening a file
14
INPUT/OUTPUT FILES : Closing a file
15
OUTPUT FILES
# include <iostream>
# include <fstream>
using namespace std;
int main()
{
double income = 123.45, expenses = 987.65;
int week = 7, year = 2006;
16
OUTPUT FILES
• You can find the L4_2.out file in the same folder as the
program that wrote the file. Open it using the notepad.
17
OUTPUT FILES
int main ()
{
ofstream myfile ("example.txt");
if (myfile.is_open())
{ myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
18
INPUT FILES
19
INPUT FILE Content of L4_3A.dat file:
• Reading data from a text file: Eg 1
# include <iostream>
# include <fstream>
#include <iomanip>
using namespace std;
int main()
{
double x; Content of L4_3B.dat file :
int i,j;
ifstream infile1("L4_3A.dat");
ifstream infile2("L4_3B.dat");
infile1>>i;
infile1>>j>>x;
infile1.close();
cout<<"From first file i = "<<i<<", j = "<<j<<", x = "<<x<<endl;
infile2>>i;
infile2>>j>>x;
infile2.close();
cout<<"From second file i = "<<i<<", j = "<<j<<", x = "<<x<<endl;
return 0;
Output displayed :
20
INPUT FILE
• Reading data from a text file: Eg 2 Content of example.txt text file :
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{ string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{ while (! myfile.eof() )
{ getline (myfile,line);
Output displayed :
cout << line << endl;
}
myfile.close();
}
else
cout << "Unable to open file";
return 0;
}
21