File I/O means reading and writing into files stored on secondary storage media like hard disks. An extensive knowledge of file I/O is absolutely essential for making and handling databases. A header file called 'fstream.h' has to be included for file operations.
For reading/writing to a file, it is necessary to open it first. The two most common methods of opening a file are - input mode which allows only read operations and output mode which allows only write operations. The syntax for opening a file are:
ifstream f1("file.dat"); // For input mode
ofstream f1("file.dat"); // For output mode
Here 'f1' is the stream name and 'file.dat' is the file required to be read or written to. After the read and write operations have been performed, it is very important to close the files. We do this using:
f1.close();
To understand the file handling operations, we take an example :-
#include<fstream.h>
#include<conio.h>
class person
{
int age;
char name[10];
public :
void input()
{
clrscr();
cout<<"Enter the name and age of the person"<<endl;
cin>>name>>age;
}
void output()
{
clrscr();
cout<<"Name = "<<name<<endl;
cout<<"Age = "<<age<<endl;
getch();
}
}obj;
void main()
{
clrscr();
obj.input();
ofstream f1("abc.txt");
f1.write((char *)&obj, sizeof(obj));
f1.close();
ifstream f2("abc.txt");
f2.read((char *)&obj, sizeof(obj));
f2.close();
obj.output();
getch();
}
Note the particular syntax of the read() and write() operations. The function sizeof() is used to calculate the size of the object to be written. Notice here that we do not include 'iostream.h' since that is already included in 'fstream.h'. Instead of the above read() and write() operations you can also write the following code:
f1<<obj; // For writing object
f2>>obj; // For reading object
References :-
Written by Rae (31 January 2005)
Rae is a member of CAU Knowledge-Bank Tutorial Writers
This article was originally published by CyberArmy.net in the CyberArmy Library.
|