CyberArmy University | Open Source Institute | CyberArmy Intelligence & Security | CyberArmy Services & Projects

[C++] Practical C++ Part 12 : File I/O


[Reply] [View by Thread] [Help]
[Back To Article Discussion Forum]

Posted by Author Rae On 2007-04-29 10:56:52




View and vote on the article here: Practical C++ Part 12 : File I/O


Practical C++ Part 12 : File I/O

Category
C++
Summary
Body
Practical C++ Part 12 : File I/O


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 imported from the CyberArmy University site. (original author: Rae)


There are no replies to this post yet.



Guest:
Subject:
Message:
Signature:
Optional Image Link:
http://

CyberArmy::Forum v0.6
Generated In 0.01409 seconds


About Us | Privacy Policy | Mission Statement | Help