Return to Topic Menu | Computer Science Main Page | MathBits.com  | Terms of Use | Resource CD

 

Using a Sequential Access File
(Reading FROM a file!)

Before you attempt to read from a sequential file, you will need to know the general format of the file and the type of data needed to receive the input.  This can be accomplished by scanning the file in text format prior to opening the file for input.  Know your file!! 

 

Steps to use (or read) a sequential access file:

1.  Declare a stream variable name:

 ifstream fin; 

//each file has its own stream buffer

ifstream is short for input file stream
fin is the stream variable name 
(and may be any legal C++ variable name.)
Naming the stream variable "fin" is helpful in remembering
that the information is coming "in" from the file.


2.  Open the file:

fin.open("myfile.dat", ios::in);

fin is the stream variable name previously declared
"myfile.dat" is the name of the file
ios::in is the steam operation mode
(your compiler may not require that you specify
the stream operation mode.)

 

3.  Read data from the file:
You MUST be aware of the necessary variable types.

//to read one number and
//one string variable

int number;
apstring item;
fin>>number>>item;

This format is OK only if the string variable is a single word.

//to read one number and
//one string variable

int number;
apstring item, dummy;
getline(fin, item);
fin>>item;
getline(fin,dummy);

This format is needed if the string variable contains whitespace.

 

4.  Close the file:

fin.close( );

Always close your files as soon as you are finished accessing information.
 

 

 

 

Required header:

<fstream.h>

allows classes ofstream and ifstream to become available.

 

 

 

A text editor can be used to view the contents of a file.  This allows you to become familiar with the variable status of an unknown file.