Files: Opening a file Using Open Function: Open Multiple Files Using Same Stream Object

Get unlimited access to the best preparation resource for UGC Political-Science: Get detailed illustrated notes covering entire syllabus: point-by-point for high retention.

Download PDF of This Page (Size: 204K)

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 run, marks.

of stream outfile (“INF”);

cout << “Enter student name”.

cin >> name.

cout << “Enter student roll number”.

cin >> run.

cout << “Enter student marks”.

cin >> marks.

outfile << name << “\n”.

outfile << run << “\n”.

outfile << marks << “\n”.

outfile. close ().

if stream in file (“INF”);

in file >> name.

in file >> run.

in file >> marks.

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

cout << “Roll no” << run << “\n”.

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

in file close ().

}

The output of the program would be:

Enter student name PARAM

Enter student roll number 20

Enter student marks 90

Name PARAM

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.

File stream _class stream _object.

Stream _object. open (“filename”).

For example:

Of stream outfile.

Out file. Open (“ABC”).

_ _ _ _ _

Out file. close ( );

Out file. open (“XYZ”);

_ _ _ _ _

Out file. close ( );

Developed by: