
Sequential Access files access the contents of a file in
sequence - hence the name. A files access pointer will
start at
the first character in the file and proceed until
the last eof(). The advantage of this method of file
access is that it is
relatively simple. It is
convenient for storing logs, trace files, and ASCII data.
The disadvantage is that, if you want
to store data that is
more complex than ASCII text, you are limited. For
many purposes, sequential access files are
fine. Let's
look at some examples:
Saving high scores
from a game to a sequential file using get():
//
void SaveHighScores(char Name[25], int score) {
ofstream highscores("hiscore.txt", ios::app);
highscores << "\nName: " << Name << " "
<< "Score: " << score << " "
<< "Monsters Fought: " << Monster::CountMonsters() << endl;
highscores.close();
} //close function
/*-------------------------------------------------------------------------------------------------------------------------*/
void DisplayHighScores() {
char contents;
ifstream highscores("hiscore.txt");
cout << "High scores for the game are:\n\n";
while(highscores.get(contents)){
cout << contents;
}
highscores.close();
}
|
Using ignore to sort
data from a sequential access file:
#include <iostream>
#include <fstream>
using namespace std;
class EmpCodes
{
public:
EmpCodes()
{
code = ' ';
salary = 0;
}
void readRecord(ifstream & InputFile)
{
InputFile >> code;
InputFile.ignore(1); //ignore the #, could have also set the delimiter
InputFile >> salary;
InputFile.ignore(1); //ignore the endl or "\n"
}
char getCode() { return code; }
int getSalary() { return salary; }
private:
char code;
int salary;
};
int main()
{
EmpCodes codeSalary;
char salaryCode = ' ';
ifstream InputFil;
InputFil.open("SalesData.txt", ios::in);
if(InputFil.is_open())
{
cout << "Enter the code: ";
cin >> salaryCode;
codeSalary.readRecord(InputFil);
while(!InputFil.eof() && toupper(salaryCode) != toupper(codeSalary.getCode()))
{
codeSalary.readRecord(InputFil);
}
if(!InputFil.eof())
cout << "Salary: " << codeSalary.getSalary() << endl;
else
cout << "Invalid code" << endl;
InputFil.close();
} //close if
else
cout << "File was not opened." << endl;
return 0;
}
Contents of data file:
A#27200
B#15000
C#23000
D#12000
E#25500 |
Using the getline()
method and a delimiter character to sort data from a sequential
file:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string PeopleName = "";
string PeopleCode = "";
string searchFor = "";
ifstream InputFile;
InputFile.open("PeopleData.txt", ios::in);
if(InputFile.is_open())
{
cout << "Enter the PeopleCode (F1, F2, P1, P2): ";
getline(cin, searchFor);
transform(searchFor.begin(), searchFor.end(), searchFor.begin(), toupper);
getline(InputFile, PeopleName, '#');
getline(InputFile, PeopleCode);
while(!InputFile.eof())
{
transform(PeopleCode.begin(), PeopleCode.end(), PeopleCode.begin(), toupper);
if(PeopleCode == searchFor)
cout << PeopleName << endl;
getline(InputFile, PeopleName, '#');
getline(InputFile, PeopleCode);
}
InputFile.close();
} //close if
else
cout << "Error opening file" << endl;
return 0;
}
Contents of data file:
Jane Doe#F1
Charles Germany#F2
Bill Clinton#F2
Drew Berrymore#P1
George Bush#P2
Kathy Ireland#P1
Mel Gibson#F1
Jacob Germany#P1
Clark Kent#F2 |
Reading data from one
file, processing it, and saving it in another sequential file:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int num = 0;
ifstream InputFile;
InputFile.open("Numbers.txt", ios::in);
ofstream OutputFile;
OutputFile.open("NewNumbers.txt", ios::out);
if(InputFile.is_open() && OutputFile.is_open())
{
InputFile >> num;
while(!InputFile.eof())
{
if( (num % 2) == 0)
OutputFile << num << endl;
InputFile >> num;
}
cout << "Saved all the even numbers to \"NumbersNew.txt\"\n\n";
InputFile.close();
OutputFile.close();
} //close if
else
cout << "Error! Can\'t open the file." << endl;
return 0;
}
Data file 1:
1
2
3
4
19
18
12
14
55
84 |
Data file 2:
2
4
18
12
14
84
|
|
Using precision()
and sequential access:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outFile;
outFile.open("prices.txt", ios::app);
float price = 0.0;
if(outFile.is_open())
{
cout << "Enter price: ";
cin >> price;
while(price > 0)
{
outFile << fixed;
outFile.precision(2);
outFile << price << endl;
cout << "Enter price: ";
cin >> price;
}
outFile.close();
} //close if
else
cout << "Error opening file." << endl;
return 0;
}
Data file:
10.50
15.99
20.00
76.54
17.34 |
Display the
average price from a sequential access file:
#include
<iostream>
#include
<fstream>
using
namespace std;
int
main()
{
ifstream inFile;
inFile.open("prices.dat", ios::in);
float price = 0.0;
int counter = 0;
float sum = 0.0;
if(inFile.is_open())
{
inFile >> price;
while(!inFile.eof())
{
counter =
counter + 1;
sum = sum +
price;
inFile >>
price;
}
inFile.close();
if(counter
> 0)
{
cout <<
fixed;
cout.precision(2);
cout <<
"Average price: " << sum / counter
<< endl;
}
else
cout << "File
is empty." << endl;
}
//close if
else
cout << "Error opening file."
<< endl;
return 0;
}
Data file
(contents of "prices.dat"):
10.50
15.99
20.00
76.54
17.34 |
Writing
multiple values to a sequential access file:
#include
<iostream>
#include
<fstream>
#include
<string>
#include
<algorithm>
using
namespace std;
int
main()
{
ofstream outFile;
outFile.open("inventory.dat", ios::out);
string invNum = "";
int quantity = 0;
float price = 0;
if(outFile.is_open())
{
cout << "Enter inventory number: ";
getline(cin, invNum);
while(invNum
!= "X" && invNum != "x")
{
transform(invNum.begin(), invNum.end(),
invNum.begin(), toupper);
cout << "Enter
quantity: ";
cin >> quantity;
cout << "Enter
price: ";
cin >> price;
cin.ignore(1);
outFile << invNum
<< '#' << quantity << "#" << price
<< endl;
cout << "Enter
inventory number: ";
getline(cin, invNum);
}
outFile.close();
}
else
cout << "Error opening file."
<< endl;
return 0;
}
Data file:
20AB#5#5.55
30CD#2#9.19
45XX#3#20.31 |
Reading multiple values in a
sequential file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("inventory.dat", ios::in);
string number = "";
int quantity = 0;
float price = 0;
float totalDol = 0;
if(inFile.is_open())
{
getline(inFile, number, '#');
inFile >> quantity;
inFile.ignore(1);
inFile >> price;
inFile.ignore(1);
while(!inFile.eof())
{
cout << "Item: " << number << endl;
cout << "Quantity: " << quantity << endl;
cout << "Price: " << price << endl;
totalDol = totalDol + (quantity * price); //accumulator
getline(inFile, number, '#');
inFile >> quantity;
inFile.ignore(1);
inFile >> price;
inFile.ignore(1);
}
inFile.close();
cout << "Total dollar value: " << totalDol << endl;
} //close if
else
cout << "Error opening file." << endl;
return 0;
}
Data file:
20AB#5#5.55
30CD#2#9.19
45XX#3#20.31 |
Uses arrays to calculate averages via a
sequential access file:
#include <iostream>
#include <fstream>
using namespace
std;
float calcTotal(float []);
float calcAvg(float []);
float calcHigh(float []);
float calcLow(float []);
int main()
{
int
x = 0;
float rainFall[12] = {0.0};
ifstream inFile;
inFile.open("RainFall.dat", ios::in);
if(inFile.is_open())
{
while(x < 12 && !inFile.eof())
{
inFile >> rainFall[x];
x = x + 1;
}
inFile.close(); //close file
cout << "Total rainfall: "
<< calcTotal(rainFall) <<
endl;
cout << "Average rainfall: "
<< calcAvg(rainFall) << endl;
cout << "Highest rainfall: "
<< calcHigh(rainFall) <<
endl;
cout << "Lowest rainfall: "
<< calcLow(rainFall) << endl;
}
else
cout << "File could not be
opened" << endl;
return 0;
}
//---------------------------------------------------------------------------------
//Function Definitions:
float calcTotal(float r[])
{
int x = 0; //keeps track of
subscripts
float total = 0.0;
//accumulator
while(x < 12)
{
total = total + r[x];
x = x + 1;
}
return total;
}//end
function
//---------------------------------------------------------------------------------
float calcAvg(float r[])
{
int
x = 0;
float
total = 0.0;
while(x < 12)
{
total = total + r[x];
x = x + 1;
}
return total / 12.0;
}
//end
function
//---------------------------------------------------------------------------------
float calcHigh(float r[])
{
int x = 1; //keeps track of
subscripts
float high = r[0]; //keeps
track of highest amount
while (x < 12)
{
if(r[x] > high)
high = r[x];
x = x + 1;
}
return high;
}
//end
function
//---------------------------------------------------------------------------------
float calcLow(float r[])
{
int
x = 1;
float
low = r[0];
while(x < 12)
{
if(r[x] < low)
low = r[x];
x = x + 1;
}
return low;
}
//end
function
Data file
"RainFall.dat":
.04
.23
.54
.63
1.54
2.16 |
2.76
2.36
2.44
1.20
.40
.07 |
|
Output:
Total rainfall: 14.37
Average rainfall: 1.1975
Highest rainfall: 2.76
Lowest rainfall: 0.04 |
Edits an existing sequential access
file:
#include <iostream>
#include <fstream>
using namespace std;
void updatePrices(float []);
void writeToFile(float []);
int main()
{
int x = 0;
float prices[10] = {0.0};
ifstream inFile;
inFile.open("Prices.txt", ios::in);
if(inFile.is_open())
{
while(x < 10 && !inFile.eof())
{
inFile >> prices[x];
x = x + 1;
}
inFile.close();
updatePrices(prices);
writeToFile(prices);
} //close if
else
cout << "File could not be opened" << endl;
return 0;
}
//---------------------------------------------------------------------------------------------------------------------------
//Functions
void updatePrices(float p[])
{
float percent = 0.0;
int num = 0;
cout << "Which item (1 - 10, 99 to stop)? ";
cin >> num;
while(num != 99)
{
if(num >= 1 && num <= 10)
{
cout << "Enter increase percentage as a whole number: ";
cin >> percent;
p[num - 1] = p[num - 1] * (1.0 + percent / 100.0);
}
else
cout << "Item number is invalid" << endl;
cout << "Which item (1 - 10, 99 to stop)? ";
cin >> num;
}
} //End function
//---------------------------------------------------------------------------------------------------------------------------
void writeToFile(float p[])
{
ofstream outFile;
outFile.open("NewPrices.txt", ios::out);
if(outFile.is_open())
{
int x = 0; //keeps track of subscripts
outFile << fixed;
outFile.precision(2);
while(x < 10)
{
outFile << p[x] << endl;
x = x + 1;
}
} //close if
else
cout << "Error opening file" << endl;
} //end function
Data
file 1:
75.00
3.50
8.99
9.50
10.30
4.55
3.00
12.69
11.00
12.34 |
Data
file 2:
90.00
3.50
11.24
9.50
10.30
4.55
3.00
12.69
11.00
10.49 |
|
Displaying students and grade
averages from a sequential file:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int
x = 0;
int minScore
= 0;
int maxScore
= 0;
int
count = 0;
int scores[20] =
{0};
ifstream inFile;
inFile.open("scores.dat",
ios::in);
if(inFile.is_open())
{
while(x < 20 && !inFile.eof())
{
inFile >> scores[x];
x = x + 1;
}
inFile.close();
//close file
cout << "Enter
minimum score: ";
cin >> minScore;
cout << "Enter
maximum score: ";
cin >> maxScore;
x = 0;
while(x < 20)
{
if(scores[x] >=
minScore && scores[x]
<= maxScore)
count = count + 1;
x = x + 1;
}
cout << "Number of
students: " << count
<< endl;
}
//end if
else
cout << "File could
not be opened" <<
endl;
return 0;
}
Data file:
100
72
88
56
78
32
88
20
99
78 |
72
88
97
20
34
75
62
100
82
56 |
|
©2004 C. Germany
|