L11 - File Input Output
L11 - File Input Output
File Input/Output
1
Review of Input/Output Features
• The input/output functionality provided by the
standard library in C++ involves stream objects.
4
Input/Output with Files
• C++ provides the following classes to perform
output and input of characters to/from files:
6
Open a File
• The first operation generally performed on an
object of one of these classes is to associate it
to a real file. This procedure is known as to
open a file.
7
Open a File
• In order to open a file with a stream object we
use its member function open():
8
Open a File
• Each one of the open() member functions of the
classes ofstream, ifstream and fstream has a
default mode that is used if the file is opened
without a second argument:
ifstream data_file;
data_file.open("numbers.dat");
data_file.close();
• We can write:
ifstream data_file("numbers.dat");
ofstream myfile;
myfile.open ("example.txt");
myfile.close();
} 12
Reading from a File
#include <iostream>
int main ()
char data[100];
ifstream myfile;
myfile.open (“example.txt");
myfile.close();
getline(myfile, line);
} 15
Read multi lines from a File
#include <iostream>
} 16
Example Problem
Read a text file containing Class Test marks of
30 students. Find the average marks obtained in
that Class Test.
17
Thank You!
18