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?
Related
Hello everyone I have been working on my lab for a few days now and I think I am close to completion. However when I go to build my program I keep getting the errors unresolved external symbol main reference in function int cdecl. Its also giving me the error of 1 unresolved externals. I am not sure what this means since I am new to writing in C++ and any help would be greatly appreciated.
Here is what I have so far
enter code here
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
string * split(string, char);
const char FileName[] = "TestAddress.txt"; //File name from where to read the characters
int _tmain()
{
menu();
return 0;
}
void menu(void) { //Display main menu and call relevant functions
char input;
while (1)
{
cout << endl;
cout << "|---------------------MENU----------------------------|" << endl; //Menu display with style
cout << "| (A)ppend Records, (S)how Records, (E)xit |" << endl; //3 options that can be selected
cout << "|-----------------------------------------------------|";
cout << endl << endl;
cin >> input;
if (input == 'A' || input == 'a')
writeData();//Append data to the file
else if (input == 'S' || input == 's')
readData(); //Read records from the file and display
else if (input == 'E' || input == 'e')
exit(0);// Exit application
else
cout << endl << "Invalid Input!!! Please try again." << endl << endl; //In case of invalid input, menu will be displayed again
}
}//end menu
void writeData(void) {//Append data to the file
string Name, Street, City, State, ZipCode, input;
fstream outputFile;
outputFile.open(FileName, fstream::app); //Open the file with append mode
do {
cout << endl << endl;
cout << "Please enter Name:" << endl;
cin >> Name; //Input Name
cout << endl;
cout << "Please enter Street:" << endl;
cin >> Street;//Input Street Address
cout << endl;
cout << "Please enter City:" << endl;
cin >> City; //Input City
cout << endl;
cout << "Please enter State:" << endl;
cin >> State;// Input State
cout << endl;
cout << "Please enter ZipCode:" << endl;
cin >> ZipCode; //Input Zipcode
cout << endl;
cout << endl;
outputFile << Name << "," << Street << "," << City << "," << State << "," << ZipCode << endl; //Write all data to the file
//Displaying the record which is input recently fromt he user
cout << endl; //Displaying heading with style
cout << "|-----------------------------------------------------|" << endl;
cout << "| Append Records |" << endl;
cout << "|-----------------------------------------------------|" << endl << endl;
cout << "Name.........." << Name << endl;
cout << "Street........" << Street << endl;
cout << "City.........." << City << endl;
cout << "State........." << State << endl;
cout << "Zip Code......" << ZipCode << endl;
cout << endl << endl;
do {
cout << "Enter Another Record?(Y/N)" << endl;
cin >> input;//In case if user wants to enter another rcord
} while (input != "Y"&& input != "y" && input != "N"&& input != "n"); //Until the user presses 'y' or 'n'
} while (input == "Y" || input == "y"); //If user wants to add another record continue or else display menu again
outputFile.close(); //Close file
}//end write data
void readData(void) {//Read records from the file and display
string Name, Street, City, State, ZipCode;
char* line = new char[2000]; //pointing to a vriable that will be having a record detail
ifstream inputFile;
int RecordNumber = 1;
inputFile.open(FileName, fstream::in);//Open the file with read mode
cout << endl;
cout << "|-----------------------------------------------------|" << endl; //Heading display with style
cout << "| Show Records |" << endl;
cout << "|-----------------------------------------------------|";
while (!inputFile.eof())
{
inputFile.getline(line, 2000); //Read one record from the file
string * fields = split(line, ',');//Split the records based on the prsence of ','
if (fields[0] == "") //In case of '\n' has encountered
continue; //Steop processing and continue the loop again
cout << "" << endl;
cout << "Record #" << RecordNumber << endl; //Displaying record with style
cout << "Name.........." << fields[0] << endl;
cout << "Street........" << fields[1] << endl;
cout << "City.........." << fields[2] << endl;
cout << "State........." << fields[3] << endl;
cout << "Zip Code......" << fields[4] << endl;
cout << endl << "-------------------------------------------------------" << endl << endl;
RecordNumber++; //Increment record number
}
}//end read data
string * split(string theLine, char theDeliminator) {
//determine how many splits there will be so we can size our array
int splitCount = 0;
for (int i = 0; i < theLine.size(); i++) { //Read the whole string (theLine) and count for all ',' encountered
if (theLine[i] == theDeliminator)
splitCount++;
}
splitCount++; //add one more to the count because there is not an ending comma
//create an array to hold the fields
string* theFieldArray;
theFieldArray = new string[splitCount];
//split the string into seperate fields
string theField = "";
int commaCount = 0;
for (int i = 0; i < theLine.size(); i++) { //read each character and look for the deliminator
if (theLine[i] != theDeliminator) {
theField += theLine[i]; //build the field
}
else { //the deliminator was hit so save to the field to the array
theFieldArray[commaCount] = theField; //save the field to the array
theField = "";
commaCount++;
}
}
theFieldArray[commaCount] = theField; //the last field is not marked with a comma...
return theFieldArray;
} //end split
hello guys i'm trying to delete a full line from a ".txt" file when the user enters the book id
my text file looks like this :
[BOOK INFO]%Book Id : 1%title : Object oriented programming%[PUBLISHER
INFO]%publisher name : misr publish house%puplisher address
:adfaf%[AUTHOR(s) INFO]%Authors Name : ahmed%Nationality :
egyptian%Authors Name : eter%Nationality : american%[MORE
INFO]%PublishedAt : 3/3/2006%status :6.
[BOOK INFO]%Book Id : 2%title : automate%[PUBLISHER INFO]%publisher
name : misr%puplisher address :nasr city%[AUTHOR(s) INFO]%Authors Name
: ahmed khaled%Nationality : egyptian%Authors Name : ohammed
adel%Nationality : egyptian%[MORE INFO]%PublishedAt : 3/8/2005%status
:15.
the line starts from [book info] to the (.)
i should be able to delete the whole line when the user enter the id
but i don't know how or what function to use
my code is :
/*password is admin*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include<stdlib.h>
#include<iomanip>
#include<conio.h>
#define F1 59
#define ESC 27
using namespace std;
void list_all_books_1();
void list_available_books_2();
void borrow_books_3();
void search_for_abook_4();
void add_new_book_5();
void delete_books_6();
fstream d_base;
char path[] = "library books.txt";
void output(){
//this function for displaying choices only
cout << setw(77) << "***********************************" << endl;
cout << setw(71) << "1. List all books in library" << endl;
cout << setw(77) << "2. List available books to borrow " << endl;
cout << setw(72) << "3. Borrow a Book from library" << endl;
cout << setw(63) << "4. Search For a Book" << endl;
cout << setw(59) << "5. Add New Books" << endl;
cout << setw(59) << "6. Delete a Book" << endl;
cout << setw(62) << "7. EXIT The Library" << endl;
cout << setw(77) << "***********************************" << endl;
}
//=====================================================================================================================================================
struct books{
//identfying books with all needed things
string id, status;
string title, p_name, p_address;
string date;
};
struct author{
string aut_name;
string aut_nationality;
};
//=====================================================================================================================================================
//function for choice 1 showing the books
void list_all_books_1(){
ifstream show;
char all;
show.open(path, ios::in | ios::app);
while (!show.eof()){
show >> std::noskipws;
show >> all;
if (all == '%')
cout << "\n";
else if (all == '.')
cout << "\n\n\n";
else
cout << all;
}
cout << endl;
show.close();
}
//=====================================================================================================================================================
void list_available_books_2(){
ifstream available_books;
char x;
available_books.open(path, ios::in | ios::app);
while (!available_books.eof()){
available_books >> std::noskipws;
available_books >> x;
if (x == '%')
cout << "\n";
else if (x == '.')
cout << "\n\n\n";
else
cout << x;
}
cout << endl;
available_books.close();
}
//=====================================================================================================================================================
void borrow_books_3(){
}
//=====================================================================================================================================================
void search_for_abook_4(){
string idx;
int offset, i = 0;
string line;
cout << "enter the ID of the book you're looking for";
cin >> idx;
d_base.open(path, ios::in | ios::app);
while (!d_base.eof()){
getline(d_base, line);
if (((offset = line.find(idx, 0))) != string::npos){
cout << "Book found" << endl;
i++;
d_base.close();
}
}
if (i == 0){
cout << "couldn't find book" << endl << endl;
}
}
//=====================================================================================================================================================
//for choice 5 to fill books
void add_new_book_5(){
int aut_number, booksnumber;
books newbook[1000];
author aut[100];
cout << "how many books you want to add ? ";
cin >> booksnumber;
cout << "what books you want to add :" << endl;
d_base.open(path, ios::out | ios::app);
for (int i = 0; i < booksnumber; i++){
cout << "id please : "; cin >> newbook[i].id;
cout << "title : "; cin.ignore(); getline(cin, newbook[i].title);
cout << "publisher name :"; getline(cin, newbook[i].p_name);
cout << "publisher address : "; getline(cin, newbook[i].p_address);
d_base << "[BOOK INFO]" << "%Book Id : " << newbook[i].id << "%title : " << newbook[i].title;
d_base << "%[PUBLISHER INFO]" << "%publisher name : " << newbook[i].p_name << "%puplisher address :" << newbook[i].p_address;
d_base << "%[AUTHOR(s) INFO]";
cout << "how many authors for the books";
cin >> aut_number;
for (int j = 0; j < aut_number; j++){
cout << "author" << j + 1 << " name : "; cin.ignore(); getline(cin, aut[j].aut_name);
cout << "Nationality : "; getline(cin, aut[j].aut_nationality);
d_base << "% Authors Name : " << aut[j].aut_name << "% Nationality : " << aut[j].aut_nationality;
}
cout << "Publish date :"; getline(cin, newbook[i].date);
cout << "How many copies of " << newbook[i].title << " "; cin >> newbook[i].status;
d_base << "%[MORE INFO]";
d_base << "%PublishedAt : " << newbook[i].date << "%status :" << newbook[i].status << "." << endl;
}
d_base.close();
cout <<setw(76)<< "Books Have Been Saved Sucessfully" << endl;
}
//=====================================================================================================================================================
void delete_books_6(){
//deleting a book
}
//=====================================================================================================================================================
int main(){
char choice;
cout << "\n\n" << setw(76) << "{ welcome to FCIS library }\n\n";
do{
output();
cout << "- what do you want to do ? ";
cin >> choice;
if (choice == '1'){
system("cls");
list_all_books_1();
}
//this one for list available books
else if (choice == '2'){
system("cls");
list_available_books_2();
}
//this one for borrow a book
else if (choice == '3'){
system("cls");
borrow_books_3();
}
else if (choice == '4'){
system("cls");
search_for_abook_4();
}
//this one is for adding new books to the list
else if (choice == '5'){
system("cls");
string pass;
do{
cout << "you must be an admin to add new books." << endl << "please enter passowrd (use small letters) : ";
cin >> pass;
if (pass == "b")
break;
else if (pass == "admin"){
system("cls");
cout << "ACCESS GAINED WELCOME " << endl;
add_new_book_5();
}
else{
cout << "Wrong password try again or press (b) to try another choice";
continue;
}
} while (pass != "admin");
}
//this one for deleteing a book
else if (choice == '6'){
system("cls");
//not completed yet
}
else if (choice == '7'){
system("cls");
cout << "\n\n\n"<<setw(76) << "Thanks for Using FCIS LIBRARY" << endl;
break;
}
else
cout << "\nwrong choice please choose again\n\n";
} while (_getch()!=27);
}
i tried to use get line and search for matching id the delete the line if there's match but couldn't accomplish it
i'm beginner at c++ by the way
Read the whole file into a memory buffer. Delete what you don't want. Overwrite the existing file with the contents of your memory buffer.
You've now deleted what you did not want from the file.
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 ¬used)
{
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 ¬used)
{
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;
}
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.";
}
}
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();
}