Home » Learn C++ » Reading Data from a File in C++

Reading Data from a File in C++

Reading Data from a File in C++:

            The data written or stored in a formatted input/output file is read back from the tile into the memory in the same order in which it is stored. The data from the file is read by opening the file in input mode. For this purpose, an object of ifstream (or fstream) class is created and the same data tile in which records are stored is attached with it. The file is automatically opened when the object is created. The data from the file is read using the extraction operator (>>) with the object.
The following program reads data from the data file “records.dat” created by the previous program.

reading-data-files

 
Program:

 

            #include <iostream.h>

            #include <fstream.h>

            #include <conio.h>

            #include <stdlib.h>

            main ()

            {

                        Char name [15];

                        int age, i=1;

                        instream rec (“records.dat”);

                        clrscr ();

                        if (!rec)

                           {

                                    cerr<< “File opening error”<<endl;

                                    exit(1);

                            }

                        while (rec)

                            {

                                    cout<< “Record #” <<i++ “:\t”;

                                    rec>>name>>age;

                                    cout<<name<< “\t” <<age <<endl;

                            }

            }

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.