Binary File - Editing - c++

Please help i am having trouble with this function. The code compiles and everything however it doesnt change anything in the file. I am so confused what i am supposed to do.... I am supposed to choose a record from the file to edit and then change it, my current code allows me to choose but when i edit the record nothing is stored?
void editRecord(Cookie &type)
{
fstream dataFile;
int num;
int count = 0;
dataFile.open("/Users/jordanmcpeek/Documents/2014_Summer/CSC_250/Unit_7/cookie.dat", ios::in | ios::out | ios::binary);
dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));
// While not at the end of the file, display the records
while (!dataFile.eof())
{
// Display the records.
cout << endl;
cout << count << ". Description: ";
cout << type.description << endl;
cout << "Quantity Sold: ";
cout << type.quantity << endl;
cout << "Price: $";
cout << type.price << endl;
dataFile.read(reinterpret_cast<char *>(&type), sizeof(type));
count++;
}
cout << "Which record would you like to edit?: ";
cin >> num;
cout << endl;
cin.ignore();
dataFile.seekp(num * sizeof(type), ios::beg);
cout << "Please enter the new description for the cookie: ";
cin.getline(type.description, SIZE);
cout << endl;
do
{
cout << endl;
cout << "Please enter the new amount sold: ";
cin >> type.quantity;
cin.ignore();
}while(type.quantity < 0);
cout << endl;
do
{
cout << "Please enter the new price: $";
cin >> type.price;
cin.ignore();
}while(type.price < 0);
cout << endl;
// Change the record
dataFile.write(reinterpret_cast<char *>(&type), sizeof(type));
dataFile.close();
}

Related

Code skips 6 lines of code on its own, what could be wrong here?

I have a problem with my code, it skips 6 lines of code, and I don't know what the problem could be. I'm just practicing C++, making a bank app, and in the registration menu it skips 6 lines of code for some reason. I would appreciate any help or suggestion! The code can look a little dirty. I don't understand why the code skips the input for the cityAddress, stateAddress, zipAddress after I type the houseAddress input.
// Registration menu code
void registerMenu() {
bool registerSuccess = false;
bool usernameSuccess = false;
string saveInfo;
system("CLS"); // Clear Console
cout << "Please create your account.\n";
cout << "First Name: ";
cin >> firstName;
cout << "Last Name: ";
cin >> lastName;
cout << "Phone Number: ";
cin >> phoneNumber;
cout << "Address: ";
cin >> houseAddress;
cout << "City: ";
cin >> cityAddress;
cout << "State: ";
cin >> stateAddress;
cout << "Zip code: ";
cin >> zipAddress;
cout << "\n\n";
cout << "Save information?\nY/N\n";
cin >> saveInfo;
if (saveInfo == "Y") {
cout << "-----------INFORMATION SAVED!-----------\n";
}
else if (saveInfo == "N") {
registerMenu();
}
else {
registerMenu();
}
cout << "\n\n";
do {
cout << "Username: ";
cin >> username;
ifstream usernameCheck("user_" + username + ".txt");
if (usernameCheck.is_open()) {
cout << "This username already exists. Create a different username.\n\n";
Sleep(1000);
}
else {
cout << "\n\t! USERNAME AVAILABLE !\n";
usernameSuccess = true;
}
} while (!usernameSuccess);
do {
cout << "Password: ";
cin >> password;
if (password.length() >= 8) {
cout << "Initial deposit to your account: $";
cin >> balance;
system("CLS"); // Clear Console
cout << "Registration complete!\n";
// [START] Create Account file
ofstream registration;
registration.open("user_" + username + ".txt");
registration << username << endl << password << endl << balance;
registration.close();
// [FINISH] Create Username file
registerSuccess = true;
password = password;
Sleep(1000);
system("CLS"); // Clear Console
cout << "--------------------------------" << endl;
cout << " Account Information\n";
cout << "Username: " << username << endl;
cout << "Password: " << password << endl;
cout << "Balance: $" << balance << endl;
cout << "--------------------------------" << endl;
cout << "Forwarding you in 5 seconds..." << endl;
Sleep(5000);
mainMenu();
}
else {
cout << "\n\nPassword must contain at least 8 characters. (You entered " << password.length() << " characters)\nPlease try again.\n";
}
} while (!registerSuccess);
}
Home addresses usually have spaces in them. Cin reads up to the first delimiter which is a space. Instead, try
std::getline(cin, houseAddress)

Reading and writing multiple structs into a file

I'm trying to store multiple structs into an file and my problem is that when I try to add 2 structs into the same file, my second struct overwrites my first struct and when I go print out my first struct, its print out my second struct. I want to have multiple structs in my file that I can display one at a time and edit them one at a time if I want. Any clue on what's wrong with my code?
int main()
{
Record record1;
Record record2;
int choice;
int choice2;
cout << "Welcome to your Records! What do you want to do today?" << endl;
cout << endl << endl;
while(choice2 != -1)
{
cout << " " << endl;
cout << "1) Add new records to the file" << endl;
cout << "2) Display any record in the file" << endl;
cout << "3) Change any record in the file" << endl;
cout << "4) Exit" << endl;
cout << "Your Choice: ";
cin >> choice;
while(choice < 1 || choice > 4)
{
cout << "Invalid choice! Enter again" << endl;
cin >> choice;
}
if(choice == 1)
{
ofstream outFile("RecordFile.dat", ios::out | ios::binary);
AddItem(outFile);
outFile.close();
}
else if(choice == 2)
{
ifstream inFile("RecordFile.dat",ios::out | ios::binary);
DisplayItem(inFile);
inFile.close();
}
else if(choice == 3)
{
ofstream outFile("RecordFile.dat", ios::out | ios::binary);
EditItem(outFile);
outFile.close();
}
else if(choice == 4)
{
choice2 = -1;
}
}
return 0;
}
Header File
struct Record
{
char name[15];
int quantity;
double wholesalecost;
double retailcost;
};
void AddItem(ofstream& outFile);
void DisplayItem(ifstream& inFile);
void EditItem(ofstream& outFile);
Functions
void AddItem(ofstream& outFile)
{
Record record;
cout << "What is the name of this record: ";
cin.ignore();
cin.getline(record.name,15);
cout << "How many do we have(quantity): ";
cin >> record.quantity;
cout << "Whats the whole sale cost: ";
cin >> record.wholesalecost;
cout << "Whats the retail cost of " << record.name << ":";
cin >> record.retailcost;
if(outFile)
{
outFile.write((char*)&(record),sizeof(record));
}
else
{
cout << "File not Found" << endl;
}
}
void DisplayItem(ifstream& inFile)
{
Record record;
int recordnum;
cout << "Enter what record number you want to display " << endl;
cin >> recordnum;
recordnum--;
if(inFile)
{
inFile.seekg(sizeof(Record) * recordnum, ios::beg);
inFile.read(reinterpret_cast<char *>(&record), sizeof(record));
cout << "Name: " << record.name << endl;
cout << "Quantity: " << record.quantity << endl;
cout << "Whole Sale Cost: " << record.wholesalecost << endl;
cout << "Retail Cost: " << record.retailcost << endl;
}
else
{
cout << "File not found" << endl;
}
}
You are writing everything to the beginning of the file, so of course multiple writes overwrite eachother.
You need to define a file format that can contain multiple records and a way to find where to write new records that doesn't overlap with previous ones, as well as an easy way to find the location of existing records.
Have you considered just using a SQL (or other type of) database?

Referencing vector causes error when running program

I am trying to make a program that will take a users input to make multiple forms. I am stuck on trying to get the vector (that will be filled with objects of the form class that the user creates) to be use-able in other functions. When I use the address-of operator (&) it gives me this error when the program gets to letting the user input the data to the objects.
This is the screen capture of the program and the error.
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Form {
public:
string Fname;
string Lname;
string City;
string Street;
string State;
string ZipCode;
};
void menuMain();
void menu1st(vector<Form> &Fvect);
void menu1st(vector<Form> &Fvect)
{
int MainM;
int n;
cout << "NEW FORM(s)" << endl;
cout << "Enter the number of forms you would like to make (Maximum of 5): "; cin >> n; cout << endl;
for (int i = 0; i < n; i++)
{
cout << "First Name: "; cin >> Fvect[i].Fname; cout << endl;
cout << "Last Name: "; cin >> Fvect[i].Lname; cout << endl;
cout << "City: "; cin >> Fvect[i].City; cout << endl;
cout << "Street: "; cin >> Fvect[i].Street; cout << endl;
cout << "State: "; cin >> Fvect[i].State; cout << endl;
cout << "Zip Code: "; cin >> Fvect[i].ZipCode; cout << endl;
}
cout << "Enter 1 to go back to main: "; cin >> MainM;
if (MainM == 1)
{
menuMain();
}
else
{
cout << "Error not a correct input." << endl;
}
}
void menu2nd()
{
int MainM;
//int Fnum;
vector<Form> Fvect;
cout << "EDIT A FORM" << endl;
cout << Fvect[1].Fname;
cout << "Enter the ";
cout << "Enter 1 to go back to main: "; cin >> MainM;
if (MainM == 1)
{
menuMain();
}
else
{
cout << "Error not a correct input." << endl;
}
}
void menuMain()
{
int Pnum;
cout << "INFORMATION FORMATTING PROGRAM" << endl;
cout << "1. Create new form's." << endl;
cout << "2. Edit a form." << endl;
cout << "3. Print forms." << endl;
cout << "4. Erase a form." << endl;
cout << "5. Exit Program." << endl;
cout << "Enter the action you want to take (1-5): "; cin >> Pnum;
vector<Form> Fvect;
if (Pnum == 1)
{
menu1st(Fvect);
}
if (Pnum == 2)
{
menu2nd();
}
else
{
cout << "Error not a correct input." << endl;
}
}
int main()
{
menuMain();
}
You are accessing Fvect using an invalid index in the following lines:
cout << "First Name: "; cin >> Fvect[i].Fname; cout << endl;
cout << "Last Name: "; cin >> Fvect[i].Lname; cout << endl;
cout << "City: "; cin >> Fvect[i].City; cout << endl;
cout << "Street: "; cin >> Fvect[i].Street; cout << endl;
cout << "State: "; cin >> Fvect[i].State; cout << endl;
cout << "Zip Code: "; cin >> Fvect[i].ZipCode; cout << endl;
Consequently, your program has undefined behavior.
You need to have items in a std::vector before you can access an item from it using the array syntax. What you need to do is:
Read the data to an object of type Form.
Add the object to the std::vector.
Replace those lines with:
Form form;
cout << "First Name: "; cin >> form.Fname; cout << endl;
cout << "Last Name: "; cin >> form.Lname; cout << endl;
cout << "City: "; cin >> form.City; cout << endl;
cout << "Street: "; cin >> form.Street; cout << endl;
cout << "State: "; cin >> form.State; cout << endl;
cout << "Zip Code: "; cin >> form.ZipCode; cout << endl;
Fvect.push_back(form);
PS
I am not sure why you have the cout << endl; in those lines. You don't need them. It will be sufficient to use:
cout << "First Name: "; cin >> form.Fname;
cout << "Last Name: "; cin >> form.Lname;
cout << "City: "; cin >> form.City;
cout << "Street: "; cin >> form.Street;
cout << "State: "; cin >> form.State;
cout << "Zip Code: "; cin >> form.ZipCode;

Item Inventory Add/Edit/View questions

Okay so i have a lot of questions for this. I was having a lot of trouble but am getting there slowly. So far I have it to where the program will read and write to a file, but it tends to repeat itself a lot. Like when reading from the file itll just keep reading the same information over and over. Also it seems to display the same record twice...and i cant test it further since it only lets me write the first record over and over without ever writing the second. Any help would be great. Also for some reason the edit function seems to pull jibberish when choosing the 1 record...so im stumped. Been working on this for hours with no luck
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
void addRecord(fstream &);
void viewRecord(fstream &);
void changeRecord(fstream &);
int menu();
const int DESC_SIZE = 21;
const int DATE_SIZE = 11;
struct inventoryData
{
char desc[DESC_SIZE]; //Desc up to 20 chars
int quantity; //Item quantity
double wholesale; //Item wholsale Cost
double retail; //Item retail Cost
char date[DATE_SIZE]; //Date able to hold info up to xx/xx/xxxx
};
int main()
{
int selection;
int recordNumber;
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
if (dataFile.fail())
{
// The file does not exist, so create it.
dataFile.open("inventory.dat", ios::out);
}
selection = menu();
while (selection != 4)
{
switch (selection)
{
case 1:
{
viewRecord(dataFile);
break;
}
case 2:
{
addRecord(dataFile);
break;
}
case 3:
{
changeRecord(dataFile);
break;
}
default:
{
cout << "Invalid - Please use 1 to 4" << endl;
break;
}
selection = menu();
}
}
dataFile.close();
return 0;
}
void addRecord(fstream &file)
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
cout << "Please enter the following data about the item" << endl;
cout << "Description: ";
cin.ignore();
cin.getline(item.desc, DESC_SIZE);
cout << "Quantity: ";
cin >> item.quantity;
cout << "Quantity: ";
cin >> item.quantity;
cout << "Wholesale cost: ";
cin >> item.wholesale;
cout << "Retail price: ";
cin >> item.retail;
cout << "Date (Please use MO/DA/YEAR format: ";
cin >> item.date;
dataFile.write(reinterpret_cast<char *>(&item), sizeof(item));
return;
}
void viewRecord(fstream &file)
{
string output;
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
fstream items;
char again;
dataFile.read(reinterpret_cast<char *>(&item), sizeof(item));
while (!items.eof())
{
// Display the record.
cout << "Description: " << item.desc << endl;
cout << "Quantity: " << item.quantity << endl;
cout << "Wholesale Cost: " << item.wholesale << endl;
cout << "Retail Cost: " << item.retail << endl;
cout << "Date: " << item.date << endl;
// Wait for the user to press the Enter key.
cout << "\nPress the Enter key to see the next record.\n";
cin.get(again);
// Read the next record from the file.
dataFile.read(reinterpret_cast<char *>(&item), sizeof(item));
}
}
void changeRecord(fstream &file)
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
int recordNumber;
cout << "Please choose a record number you want to edit" << endl;
cin >> recordNumber;
dataFile.seekg(recordNumber * sizeof(item), ios::beg);
dataFile.read(reinterpret_cast<char *>(&item), sizeof(item));
cout << "Description: " << item.desc << endl;
cout << "Quantity: " << item.quantity << endl;
cout << "Wholesale cost: " << item.wholesale << endl;
cout << "Retail price: " << item.retail << endl;
cout << "Date: " << item.date << endl;
cout << endl;
// Get the new record data.
cout << "Enter the new data:\n";
cout << "Description: ";
cin.ignore();
cin.getline(item.desc, DESC_SIZE);
cout << "Quantity: ";
cin >> item.quantity;
cout << "Quantity: ";
cin >> item.quantity;
cout << "Wholesale cost: ";
cin >> item.wholesale;
cout << "Retail price: ";
cin >> item.retail;
cout << "Date (Please use MO/DA/YEAR format: ";
cin >> item.date;
// Move back to the beginning of this record's position
dataFile.seekp(recordNumber * sizeof(item), ios::beg);
// Write new record over the current record
dataFile.write(reinterpret_cast<char *>(&item), sizeof(item));
}
int menu()
{
int menuSelection;
cout << fixed << showpoint << setprecision(2);
cout << "----------Inventory----------" << endl;
cout << "1 - View inventory" << endl;
cout << "2 - Add an item" << endl;
cout << "3 - Edit an item" << endl;
cout << "4 - End Program" << endl;
cin >> menuSelection;
if (!cin)
{
cout << "Invalid - Please use 1 to 4" << endl;
cin >> menuSelection;
}
if (menuSelection < 1 || menuSelection > 4)
{
cout << "Invalid - Please use 1 to 4" << endl;
cin >> menuSelection;
}
return menuSelection;
}
int menu()
{
int menuSelection = 0;//initialize
cout << fixed << showpoint << setprecision(2);
cout << "----------Inventory----------" << endl;
cout << "1 - View inventory" << endl;
cout << "2 - Add an item" << endl;
cout << "3 - Edit an item" << endl;
cout << "4 - End Program" << endl;
//*** flush cin, this is inside a loop, it can cause problems
cin.clear();
fflush(stdin);
cin >> menuSelection;
return menuSelection;
}
int main()
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
if (dataFile.fail())
{
// The file does not exist, so create it.
dataFile.open("inventory.dat", ios::out);
dataFile.close();
}
for (;;)
{
int selection = menu();
if (selection == 4)
break;
switch (selection)
{
case 1:
viewRecord(dataFile);
break;
case 2:
addRecord(dataFile);
break;
case 3:
changeRecord(dataFile);
break;
default:
cout << "Invalid - Please use 1 to 4" << endl;
break;
}
}
return 0;
}
void viewRecord(fstream &notused)
{
fstream dataFile("inventory.dat", ios::in | ios::out | ios::binary);
inventoryData item;
while (dataFile)
{
dataFile.read(reinterpret_cast<char*>(&item), sizeof(item));
// Display the record.
cout << "Description: " << item.desc << endl;
cout << "Quantity: " << item.quantity << endl;
cout << "Wholesale Cost: " << item.wholesale << endl;
cout << "Retail Cost: " << item.retail << endl;
cout << "Date: " << item.date << endl;
cout << endl;
}
}
void addRecord(fstream &notused)
{
fstream file("inventory.dat", ios::in | ios::out | ios::app | ios::binary);
inventoryData item;
cout << "Please enter the following data about the item" << endl;
cout << "Description: ";
cin.ignore();
cin.getline(item.desc, DESC_SIZE);
cout << "Quantity: ";
cin >> item.quantity;
cout << "Wholesale cost: ";
cin >> item.wholesale;
cout << "Retail price: ";
cin >> item.retail;
cout << "Date (Please use MO/DA/YEAR format: ";
cin.getline(item.desc, DATE_SIZE);
file.write(reinterpret_cast<char *>(&item), sizeof(item));
return;
}

Program reading from variables stored in itself and not from binary file

I'm working on a program very important to my programming class, and there's something I can't quite figure out; When I try to read from a binary file I've created after opening the program, it fails even if the file's in the directory, and after I try to wipe the contents of the file, I can still 'read' them from the file even though said file is empty when I examine it in explorer. I've determined from this that even though I'm using BinaryFile.read, it's not truly reading from the file, and instead reading from variables stored in the program itself. How can I get my program to read from the actual file?
(please note that this is not yet a complete program, hence the commented sections and empty functions.)
(Also please note that, due to the nature of my class, I am only allowed to use what has been taught already (namely, anything in the fstream header and most things before which are necessary to make a basic program - he's letting me use things in stdio.h, as well.)
//
// main.cpp
// Binary Program
//
// Created by Henry Fowler on 11/19/14.
// Copyright (c) 2014 Bergen Community College. All rights reserved.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
#include <math.h>
#include <stdio.h>
using namespace std;
struct Record
{
char Name[20];
char LastName[20];
double Pay;
int Clearance;
int ID;
};
void CreateFile(fstream&); //Working
void CheckExist(fstream&); //Working
void Populate(fstream&,Record[],int&,int&); //Working
void Display(fstream&,Record[],int&,int&); //Working
void Append(fstream&,Record[],int&,int&); //Working
void DeleteFromFile(fstream&,fstream&,Record[],int&,int&);
// void SearchInFile(fstream&,Record[],int&,int&);
// void ModifyRecord(fstream&,Record[],int&,int&);
//void SortFile();
void WipeFile(fstream&);
void DelFile(fstream&);
int main(int argc, const char * argv[])
{
Record EmpRecords[20];
char Binary[] = "BinaryFile.dat";
char Binary2[] = "BinaryFileTemp.dat";
int maxsize; //make sure to set i to max size so you can use it later for things like wiping the file or deleting specific records
fstream BinaryFile;
fstream BinaryFile2;
string InputStr;
// char Read;
//int Choice = 0;
int i = 0;
int choice = 0;
int switchchoice;
CreateFile(BinaryFile); //working
CheckExist(BinaryFile); //working
BinaryFile.close();
while(choice==0)
{
cout << "Options: " << endl;
cout << "End Program (0)" << endl;
cout << "Input new records to file (1)" << endl;
cout << "Display current contents of file (2)" << endl;
cout << "Append a record at the end of the file (3)" << endl;
cout << "Delete a record from the file (4)" << endl;
cout << "Search for a record in the file (5)" << endl;
cout << "Modify a certain record (6)" << endl;
cout << "Sort file (unimplemented)" << endl;
cout << "Wipe contents of file (8)" << endl;
cout << "Please choose an option: ";
cin >> switchchoice;
switch(switchchoice)
{
case 0:
{
cout << "Exiting.";
BinaryFile.close();
system("PAUSE");
return 0;
break;
}
case 1:
{
Populate(BinaryFile, EmpRecords,i,maxsize); //working
break;
}
case 2:
{
Display(BinaryFile, EmpRecords,i,maxsize); //working i think
break;
}
case 3:
{
Append(BinaryFile, EmpRecords,i,maxsize); //working
break;
}
case 4:
{
DeleteFromFile(BinaryFile,BinaryFile2,EmpRecords,i,maxsize); //!
break;
}
case 5:
{
// SearchInFile(BinaryFile, EmpRecords,i,maxsize); //!
break;
}
case 6:
{
// ModifyRecord(BinaryFile, EmpRecords,i,maxsize); //!
break;
}
case 7:
{
cout << "Error, file sorting is currently unimplemented. Please try again.";
break;
}
case 8:
{
WipeFile(BinaryFile);
break;
}
}
}
system("PAUSE");
return 0;
}
void CreateFile(fstream& BinaryFile)
{
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary);
}
void CheckExist(fstream &BinaryFile)
{
if(BinaryFile.good())
{
cout << endl << "File does exist" << endl;
}
else
{
cout << "file named can not be found \n";
system("PAUSE");
}
}
void Populate(fstream &BinaryFile,Record EmpRecords[],int &i, int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary);
int choice = 0;
while(choice==0)
{
cout << "Please input employee first name: ";
cin >> EmpRecords[i].Name;
cout << "Please input employee last name: ";
cin >> EmpRecords[i].LastName;
cout << "Please input Employee Pay: ";
cin >> EmpRecords[i].Pay;
cout << "Please input Employee Clearance (1-10): ";
cin >> EmpRecords[i].Clearance;
cout << "Please input Employee ID (6 numbers, i.e. 122934): ";
cin >> EmpRecords[i].ID;
cout << "Input another employee's information? (0) = yes, (1) = no: ";
cin >> choice;
BinaryFile.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
i = i+1;
}
maxsize = i;
cout << "i is " << i << endl;
cout << "maxsize is " << maxsize << endl;
BinaryFile.close();
}
void Display(fstream &BinaryFile,Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::in | ios::binary | ios::app);
int i2 = maxsize;
i = 0;
while(i2>0)
{
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << i << endl;
cout << EmpRecords[i].Name << " " << EmpRecords[i].LastName << endl;
cout << "Pay: $" << EmpRecords[i].Pay << endl;
cout << "Clearance: " << EmpRecords[i].Clearance << endl;
cout << "Employee ID: " << EmpRecords[i].ID << endl;
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << endl;
i2 = i2-1;
i = i+1;
}
BinaryFile.close();
}
void Append(fstream &BinaryFile,Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out|ios::binary|ios::ate|ios::app);
cout << "Please input employee first name: ";
cin >> EmpRecords[maxsize].Name;
cout << "Please input employee last name: ";
cin >> EmpRecords[maxsize].LastName;
cout << "Please input Employee Pay: ";
cin >> EmpRecords[maxsize].Pay;
cout << "Please input Employee Clearance (1-10): ";
cin >> EmpRecords[maxsize].Clearance;
cout << "Please input Employee ID (6 numbers, i.e. 122934): ";
cin >> EmpRecords[maxsize].ID;
cout << "Input another employee's information? (0) = yes, (1) = no: ";
BinaryFile.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
maxsize = maxsize+1;
cout << "maxsize is " << maxsize << endl;
BinaryFile.close();
}
void DeleteFromFile(fstream &BinaryFile,fstream &BinaryFile2, Record EmpRecords[],int &i,int &maxsize)
{
BinaryFile.open("BinaryFile.dat", ios::out|ios::binary|ios::app);
BinaryFile2.open("BinaryFileTemp.dat", ios::out|ios::binary|ios::app);
int Choice;
cout << "Would you like to delete a file by name or by employee number?" << endl;
cout << "Name (1)" << endl;
cout << "Number (2)" << endl;
cout << "Choice: ";
cin >> Choice;
int i2 = maxsize;
if(Choice==1)
{
cout << "Please input employee first name: ";
// cin >> firstname;
cout << "Please input employee last name: ";
// cin >> lastname;
cout << "Searching...";
int i2 = maxsize;
i = 0;
while(i2>0)
{
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
cout << i << endl;
BinaryFile.read((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
// if(EmpRecords[i].Name == firstname)
// {
// cout << "Found first name." << endl;
// if (EmpRecords[i].LastName == lastname)
// {
// cout << "Found last name." << endl;
/// }
// }
// else
// {
// cout << "Could not find name.";
// // BinaryFile2.write((char *) (&EmpRecords[i]),sizeof(EmpRecords[i]));
// }
cout << endl;
i2 = i2-1;
i = i+1;
}
}
BinaryFile.close();
if( remove( "BinaryFile.dat" ) != 0 )
cout << endl << "Error deleting file" << endl;
else
{
cout << "File successfully deleted" << endl << endl;
}
int result;
char oldname[]="BinaryFileTemp.dat";
char newname[]="BinaryFile.dat";
result = rename(oldname,newname);
if(result == 0)
cout << "DEBUG: Success" << endl;
else
cout << "DEBUG: Failure" << endl;
}
void WipeFile(fstream &BinaryFile)
{
int sure;
cout << "There is no undoing this action." << endl;
cout << "Continue (1)" << endl;
cout << "Cancel (2)" << endl;
cout << "Wipe file? ";
cin >> sure;
if(sure == 1)
{
cout << "Wiping file.";
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary | ios::trunc);
BinaryFile.close();
}
else
{
cout << "Canceling.";
}
}
void DelFile(fstream &BinaryFile)
{
BinaryFile.close();
if( remove( "BinaryFile.dat" ) != 0 )
cout << endl << "Error deleting file" << endl;
else
{
cout << "File successfully deleted" << endl << endl;
}
}
Here the problem seems to be, even though you are wiping the file contents, you are not clearing the data you had stored in Record EmpRecords[20]; or the int maxsize value.
Few things you can do inside void WipeFile(fstream &BinaryFile) function: To keep it simple, we'll just reset maxsize to 0:
Pass the maxsize variable as reference to WipeFile(), the same way you are passing for Populate()
Update maxsize = 0, to indicate all the records are removed, when you delete the file contents.
It is better to memset the contents of EmpRecords as well similarly.
For now, I just modified your code to reset maxsize to 0 in WipeFile() and it worked.
void WipeFile(fstream &BinaryFile, int &maxsize)
{
int sure;
cout << "There is no undoing this action." << endl;
cout << "Continue (1)" << endl;
cout << "Cancel (2)" << endl;
cout << "Wipe file? ";
cin >> sure;
if(sure == 1)
{
cout << "Wiping file.";
BinaryFile.open("BinaryFile.dat", ios::out | ios::binary | ios::trunc);
BinaryFile.close();
maxsize = 0;
}
else
{
cout << "Cancelling.";
}
}