Well, that helps some, but still doesn't work quite right. When the program runs and asks for the user to enter tool name, quantity and cost, it hangs until any other character is entered. It also doesn't seem to overwrite the two zeros in the last two initialized fields; the quantity and cost entered display, but so do the zeros the fields have when initialized. All help is appreciated, thanks. Here's the whole code so far:
Code:
#include <iostream>
#include <fstream>
#include <cstdlib>
//#include <iomanip>
using namespace std;
#include "toolList.h"
void initialize(ofstream &);
void enterTool(fstream &);
void printTool(fstream &);
int main()
{
// Create file and initialize with 100 blank records
ofstream toolSet("hardware.dat", ios::binary);
initialize(toolSet);
// Open file for read/write, check if successful
fstream hardware("hardware.dat", ios::in | ios::out | ios::binary);
if (!hardware)
{
cerr << "File not opened" << endl;
exit(EXIT_FAILURE);
}
enterTool(hardware); // Enter records in file
printTool(hardware); // Print file to screen
return 0; // That's all, folks!
}
/////////////////////////////////////////////////////////////////////////////
// Initialize 100 blank records
void initialize(ofstream &toolInit)
{
toolList toolRecord = {0, "tool", 0, 0}; // Blank record
for (int i = 0; i < 100; i++)
toolInit.write((char *)&toolRecord, sizeof(toolList)); // Write blank record
toolInit.close(); // Close file
}
/////////////////////////////////////////////////////////////////////////////
// Enter data into records
void enterTool(fstream &toolFile)
{
int rec; // Record number to enter
toolList tool;
cout << "\nEnter a record number from 1 - 100: ";
cin >> rec;
cin.ignore();
toolFile.seekg((rec - 1) * sizeof(toolList)); // Move to selected record
toolFile.read((char *)&tool, sizeof(toolList)); // Read selected record
if (tool.recNum == 0) // Make sure record is blank
{
cout << "\nEnter tool name, quantity and cost: ";
// cin.ignore();
cin.getline(tool.toolName, 25);
cin >> tool.quant >> tool.cost;
tool.recNum = rec;
toolFile.seekp((rec - 1) * sizeof(toolList));
toolFile.write((char *)&tool, sizeof(toolList));
}
else // Record number already has data
cerr << "\nRecord number " << rec << " in use" << endl;
}
//////////////////////////////////////////////////////////////////////////////
// Print file to screen
void printTool(fstream &toolPrint)
{
toolList toolRecord;
toolPrint.seekp(0); // Begin at start of file
cout << "Record # Tool Name Quantity Cost" << endl;
cout << "_______________________________________" << endl << endl;
toolPrint.read((char *)&toolRecord, sizeof(toolList));
while (!toolPrint.eof())
{
if (toolRecord.recNum != 0)
cout << toolRecord.recNum << toolRecord.toolName
<< toolRecord.quant << toolRecord.cost << endl;
toolPrint.read((char *)&toolRecord, sizeof(toolList));
}
}