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.
|