NIOS Computer Science: Chapter 16 – Files Part 2

Download PDF of This Page (Size: 197K)

Image of opening files using open()

Image of Opening Files Using Open()

Image of opening files using open()

The following program uses a single file for both writing and reading purposes. First, it takes the data form the keyboard and writes it to the file. After the writing is completed, the file is closed. The program again opens the same file, reads the information already written to it and displays it on the screen.

# include<fstream.h>

void main ( )


char name [30];

int rn, marks;

ofstream outfile ( “INF”);

cout << “Enter student name”;

cin >> name;

cout << “Enter student roll number”;

cin >> rn;

cout << “Enter student marks”;

cin >> marks;

outfile << name << “\n”;

outfile << rn << “\n”;

outfile << marks << “\n”;

outfile . close ( );

ifstream infile ( “INF” );

infile >> name;

infile >> rn;

infile >> marks;

cout << “Name” << name << “\n”;

cout << “Roll no” << rn << “\n”;

cout << “Marks” << marks << “\n”;

infile close ( );


The output of the program would be:

Enter student name PARAM

Enter student roll number 20

Enter student marks 90


Roll No. 20

Marks 90

Opening a File Using Open ( ) Function

The function open ( ) can be used to multiple files that use the same stream object.

First a stream object is assigned to and then it is used to open the file in turn.

filestream_class stream_object; (“filename”);

For example :

ofstream outfile;“ABC”);

_ _ _ _ _

outfile.close ( ); (“XYZ”);

_ _ _ _ _

outfile.close ( );

Doorsteptutor material for UGC is prepared by worlds top subject experts- Get full length tests using official NTA interface: all topics with exact weightage, real exam experience, detailed analytics, comparison and rankings, & questions with full solutions.

Developed by: