i am creating this program that stores some items into the (.dat) file..
the program seems to run smoothly but when i try to read the data from the file i see special character on my screen and none of the data that i was trying to save, was saved properly, note that when i run the similar code in main() it works and it actually shows me the correct output.. please help me on this i really don't know what to do here
void viewFile() {
Product item;
ifstream file("products.dat", ios::binary);
if (!file.read(reinterpret_cast<char*>(&item), sizeof(Product))) {
cout <<"failed to read";
system("exit");
}
item.viewProduct();
while (!file.eof()) {
item.viewProduct();
cout <<endl <<endl;
file.read((char *)(&item), sizeof(Product));
}
file.close();
}
void addProductToInventory() {
string name;
int quantity;
int pricePerItem;
ofstream obj("products.dat", ios::out | ios::binary);
Product item;
int numberOfProducts;
cout <<"enter the number of products you want to add in this inventory: ";
cin >> numberOfProducts;
for (int counter = 1; counter <= numberOfProducts; counter++) {
Product product;
cout <<"enter the name of the object: ";
cin >> name;
cout <<"enter the quantity of the product: ";
cin >> quantity;
cout <<"enter the price of this product (per item): ";
cin >> pricePerItem;
product.setName(name);
product.setQuantity(quantity);
product.setPricePerItem(pricePerItem);
if (!obj.write(reinterpret_cast<char*>(&product), sizeof(Product))) {
cout <<"failed writing\n";
system("exit");
}
cout <<"item added\n\n";
}
obj.flush();
obj.close();
}
this is my code in main() which WORKS its exactly the same code.. i guess
ofstream file ("products.dat", ios::out | ios::binary | ios::trunc);
Product p1("hammer", 12, 3);
Product p2("screw driver", 43, 1);
if (!file.write(reinterpret_cast<char*>(&p1), sizeof(Product))) {
cout <<"failed to write";
system("exit");
}
file.write(reinterpret_cast<char*>(&p2), sizeof(Product));
file.close();
ifstream file2("products.dat", ios::out | ios::binary);
if (!file2.read(reinterpret_cast<char*>(&p1), sizeof(Product))) {
cout <<"failed to read";
system("exit");
}
while (!file2.eof()) {
p1.viewProduct();
cout <<endl <<endl;
file2.read((char *)(&p1), sizeof(Product));
}
file2.close();
}
P.S i am really sorry if this comes out to be a messy question.. I have been debugging this for hours and now i can't even think straight.
Lets start by thinking about how pointers work.
char* a = new char[2];
a[0] = 'a';
a[1] = 'b';
char* b = a;
std::cout << a[0] << a[1]; //prints ab
std::cout << b[0] << b[1]; //prints ab
a[1] = 'c';
std::cout << b[0] << b[1]; //prints ac
delete[] a;
std::cout << b[0] << b[1]; //prints random garbage because the memory that b points at is deleted
know lets start writing these pointers to files
char* a = new char[2];
a[0] = 'a';
a[1] = 'b';
ofstream outFile("products.dat", ios::binary | ios::trunc);
outFile.write(reinterpret_cast<char*>(&a), sizeof(a));
outFile.close();
{
ifstream inFile("products.dat", ios::binary);
char* b;
inFile.read(reinterpret_cast<char*>(&b), sizeof(b));
std::cout << b[0] << b[1]; //prints ab
a[1] = 'c';
std::cout << b[0] << b[1]; //prints ac
}
delete[] a;
{
ifstream inFile("products.dat", ios::binary);
char* b;
inFile.read(reinterpret_cast<char*>(&b), sizeof(b));
std::cout << b[0] << b[1];//prints random garbage because the memory that b points at is deleted
}
std::string contains pointers to dynamically allocated memory.
You should do something like this.
void viewFile() {
ifstream file("products.dat", ios::binary);
while (!file.eof()) {
int nameLength = 0;
if (!file.read(reinterpret_cast<char*>(&nameLength), sizeof(nameLength))) {
cout <<"failed to read";
system("exit");
}
std::string name{ nameLength, '?' };
if (!file.read(name.data(), sizeof(char) * nameLength) {
cout <<"failed to read";
system("exit");
}
int quantity;
if (!file.read(reinterpret_cast<char*>(&quantity), sizeof(quantity)) {
cout <<"failed to read";
system("exit");
}
int pricePerItem;
if (!file.read(reinterpret_cast<char*>(&pricePerItem), sizeof(pricePerItem)) {
cout <<"failed to read";
system("exit");
}
Product item{ std::move(name),quantity, pricePerItem };
item.viewProduct();
}
file.close();
}
void addProductToInventory() {
string name;
int quantity;
int pricePerItem;
ofstream obj("products.dat", ios::out | ios::binary);
int numberOfProducts;
cout <<"enter the number of products you want to add in this inventory: ";
cin >> numberOfProducts;
for (int counter = 1; counter <= numberOfProducts; counter++) {
cout <<"enter the name of the object: ";
cin >> name;
cout <<"enter the quantity of the product: ";
cin >> quantity;
cout <<"enter the price of this product (per item): ";
cin >> pricePerItem;
int nameLength = name.size();
if (!obj.write(reinterpret_cast<char*>(&nameLength), sizeof(nameLength))) {
cout <<"failed writing\n";
system("exit");
}
if (!obj.write(name.data(), sizeof(char) * nameLength) {
cout <<"failed writing\n";
system("exit");
}
if (!obj.write(reinterpret_cast<char*>(&quantity), sizeof(quantity))) {
cout <<"failed writing\n";
system("exit");
}
if (!obj.write(reinterpret_cast<char*>(&pricePerItem), sizeof(pricePerItem))) {
cout <<"failed writing\n";
system("exit");
}
cout <<"item added\n\n";
}
obj.flush();
obj.close();
}
Related
I created my program in Visual Studio, it works perfectly the input / output etc. are all correct. When I run it in AWS Cloud 9 or Mirmir I get the same error message, What does this mean? How should I modify it to work in AWS? I thought C++ codes work in all IDE which supports C++. The errors are:
In constructor ‘Departments::Departments(int, char*, char*)’:
error: ‘strcpy_s’ was not declared in this scope
strcpy_s(Departmentname, nameOfDepartment);
^
In constructor ‘Employee::Employee(int, char*, double, double, int)’:
error: ‘strcpy_s’ was not declared in this scope
strcpy_s(emploeename, nameOfTheEmployee);
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;
const int SizeForString = 100;
char deptartmentRecordFileName[100] = "departments.dat ";
char employeeRecordFileName[100] = "employees.dat";
struct Departments {
int DepartmentID;
char Departmentname[SizeForString];
char DepartmentHeadName[SizeForString];
Departments()
{
}
Departments(int idOfTheDepartment, char nameOfDepartment[], char headNameOfDepartment[])
{
DepartmentID = idOfTheDepartment;
strcpy_s(Departmentname, nameOfDepartment);
strcpy_s(DepartmentHeadName, headNameOfDepartment);
}
};
struct Employee {
int employeeID;
char emploeename[SizeForString];
double employeesalary;
double employeeage;
int employeeDepartmentID;
Employee()
{
}
Employee(int idOfTheEmployee, char nameOfTheEmployee[], double salaryOfTheEmployee, double ageOfTheEmployee, int departmentId)
{
employeeID = idOfTheEmployee;
strcpy_s(emploeename, nameOfTheEmployee);
employeesalary = salaryOfTheEmployee;
employeeage = ageOfTheEmployee;
employeeDepartmentID = departmentId;
}
};
bool DepartmentIdCheck (int id)
{
Departments temp;
ifstream myfile1(deptartmentRecordFileName, ios::in | ios::binary | ios::app);
if (!myfile1)
{
cout << "Error To Open File.\n";
return false;
}
while (myfile1.read((char*)&temp, sizeof(Departments)))
{
if (temp.DepartmentID == id)
{
myfile1.close();
return true;
}
}
myfile1.close();
return false;
}
bool checkIDEmplyee (int id)
{
Employee temp;
ifstream myfile1(employeeRecordFileName, ios::in | ios::binary | ios::app);
if (!myfile1)
{
cout << "Error To Open File.\n";
return false;
}
while (myfile1.read((char*)&temp, sizeof(Employee)))
{
if (temp.employeeID == id)
{
myfile1.close();
return true;
}
}
myfile1.close();
return false;
}
void writeDepartmentData(Departments temp)
{
ofstream myfile1(deptartmentRecordFileName, ios::out | ios::binary | ios::app);
if (!myfile1)
{
cout << "Error To Open File.\n";
return;
}
myfile1.write((char*)&temp, sizeof(Departments));
myfile1.close();;
}
void writeEmployeeData(Employee temp)
{
ofstream myfile1(employeeRecordFileName, ios::out | ios::binary | ios::app);
if (!myfile1)
{
cout << "Error To Open File.\n";
return;
}
myfile1.write((char*)&temp, sizeof(Employee));
myfile1.close();
}
void createReport()
{
double totalSalary = 0;
Departments depTemp;
ifstream myfile1(deptartmentRecordFileName, ios::in | ios::binary | ios::app);
if (!myfile1)
{
cout << "Error To Open File.\n";
return;
}
while (myfile1.read((char*)&depTemp, sizeof(Departments)))
{
Employee empTemp;
ifstream myfile2(employeeRecordFileName, ios::in | ios::binary | ios::app);
while (myfile2.read((char*)&empTemp, sizeof(Employee)))
{
if (!myfile1)
{
cout << "Error To Open File.\n";
return;
}
if (depTemp.DepartmentID == empTemp.employeeDepartmentID)
{
totalSalary += empTemp.employeesalary;
}
}
cout << "Dept : " << depTemp.Departmentname << endl;
cout << "Total Salary : $" << totalSalary << endl << endl;
myfile2.close();
totalSalary = 0;
}
myfile1.close();
}
int main()
{
int choice = 0;
while (choice != 4)
{
cout << "\nHuman Resources Menu";
cout << "\n1. Create Department"
"\n2. Create Employee"
"\n3. Display Salary Report"
"\n4. -- Quit -- " << endl;
cout << "Please make a selection : ";
cin >> choice;
if (choice == 1)
{
int deptIdInput;
char nameDeptInput[SizeForString];
char headNameInput[SizeForString];
cout << "Please Enter Department Details:" << endl;
cout << "Department ID : ";
cin >> deptIdInput;
bool IdExit = DepartmentIdCheck (deptIdInput);
if (IdExit)
{
cout << "Value must be unique!" << endl;
continue;
}
cout << "Department Name : ";
cin >> nameDeptInput, SizeForString;
cout << "Head of Department : ";
cin >> headNameInput;
Departments d(deptIdInput, nameDeptInput, headNameInput);
writeDepartmentData(d);
}
else if (choice == 2)
{
int idEmploy;
char nameEmploy[SizeForString];
double salaryEmploy;
double ageEmploy;
int departmentIdForEmploy;
cout << "Please Enter Employee Details:" << endl;
cout << "Employee ID : ";
cin >> idEmploy;
bool IdExit = checkIDEmplyee (idEmploy);
if (IdExit)
{
cout << "Value must be unique !" << endl;
continue;
}
cout << "Employee Name : ";
cin >> nameEmploy;
cin.ignore();
cout << "Salary: $";
cin >> salaryEmploy;
cout << "Age : ";
cin >> ageEmploy;
cout << "Department ID : ";
cin >> departmentIdForEmploy;
bool foundId = DepartmentIdCheck (departmentIdForEmploy);
while (!foundId)
{
cout << "Please enter a valid department ID : ";
cin >> departmentIdForEmploy;
foundId = DepartmentIdCheck (departmentIdForEmploy);
}
Employee e(idEmploy, nameEmploy, salaryEmploy, ageEmploy, departmentIdForEmploy);
writeEmployeeData(e);
}
else if (choice == 3)
{
createReport();
}
else if (choice != 4)
{
cout << "Please enter a valid choice" << endl;
}
}
}
Your Visual Studio IDE may have loaded in libraries for you that your other IDEs do not. It looks like strcpy is part of the <cstring> library. You will need to #include <cstring> to use it.
Visual Studio runs on Windows while Cloud9 runs on linux. They use different compilers with different standard libraries.
Is this correct?
Here Update is member function of Product class.
I am using this pointer(pointing to calling product object) to read objects stored in file over and over.
file.read((char *)this, sizeof(product));
Here if the class(see the update member function):
class product
{
int product_num;
string product_name;
int quantity;
float sell_p;
float buy_p;
int gst;
float total;
float profit;
public:
void calculate()
{
this->total = this->quantity * (this->sell_p);
this->profit = this->total - (this->buy_p * this->quantity) * (1 + this->gst / 100);
}
product()
{
product_num = 0;
product_name = "\0";
}
product(int p_num, string name, int quantity, float sell_p, float buy_p, int gst)
{
this->product_num = p_num;
this->product_name = name;
this->quantity = quantity;
this->sell_p = sell_p;
this->buy_p = buy_p;
this->gst = gst;
calculate();
}
void get_data()
{
cout << "Enter Serial Number: ";
cin >> this->product_num;
cout << "Enter Product Name(MAX LENGTH: 20): ";
cin>>this->product_name;
cout << "Enter Quantity: ";
cin >> this->quantity;
cout << "Enter Buying Price: ";
cin >> this->buy_p;
cout << "Enter GST: ";
cin >> this->gst;
cout << "Enter Selling Price: (Selling Price should be greater than " << (this->buy_p + (this->gst / 100) * this->buy_p) << " to turn profit)";
cin >> this->sell_p;
calculate();
}
void show_product()
{
cout << "Serial: " << this->product_num
<< "\nName: " << this->product_name
<< "\nQuantity: " << this->quantity
<< "\nSelling Price: " << this->sell_p
<< "\nBuying Price: " << this->buy_p
<< "\nGST: " << this->gst << endl;
}
bool remove_product(int x)
{
if (x > this->quantity)
return false;
this->quantity -= x;
return true;
}
int getSerialNumber()
{
return this->product_num;
}
string getName()
{
return this->product_name;
}
int getQuantity()
{
return this->quantity;
}
int getGST()
{
return this->gst;
}
float getTotal()
{
return this->total;
}
float getProfit()
{
return this->profit;
}
float getSellPrice()
{
return this->sell_p;
}
float getBuyPrice()
{
return this->buy_p;
}
bool isValid()
{
if (product_num == 0 || product_name == "\0")
return false;
return true;
}
void save()
{
ofstream fout;
fout.open("product.dat", ios::binary | ios::app);
if (!fout)
{
cout << "Failed To Open File!!\nExiting..";
exit(0);
}
else
{
fout.write((char *)this, sizeof(product));
}
fout.close();
}
void update()
{
int s_num = this->product_num;
fstream file;
file.open("product.dat", ios::binary | ios::ate | ios::in | ios::out);
if (!file)
{
cout << "Failed to open file!!!\nExiting...." << endl;
exit(0);
}
else
{
file.seekg(0);
file.read((char *)this, sizeof(product));
while (!file.eof())
{
if (s_num == this->product_num)
{
cout << "Product Detail: ";
this->show_product();
cout << "Enter the Values: " << endl;
cout << "Note: IF DONT WISH TO CHANGE KINDLY ENTER SAME VALUE.";
this->get_data();
file.seekp(-(sizeof(product)),ios::cur);
file.write((char *)this, sizeof(product));
break;
}
file.read((char *)this, sizeof(product));
}
}
file.close();
}
void remove_it()
{
int s_num = this->product_num;
ofstream fout;
ifstream fin;
fin.open("product.dat", ios::in | ios::binary);
if (!fin)
{
cout << "Failed to open file!!\nExiting...";
exit(0);
}
else
{
fout.open("temp.dat", ios::binary | ios::out);
fin.read((char *)this, sizeof(product));
while (!fin.eof())
{
if (!(s_num == this->product_num))
{
fout.write((char *)this, sizeof(product));
}
fin.read((char *)this, sizeof(product));
}
fin.close();
fout.close();
if(remove("product.dat") == 0)
cout<<"Sucessfully Deleted file\n";
else
cout<<"File Removal Failed\n";
if(rename("temp.dat", "product.dat") == 0)
cout<<"Successfully Renamed\n";
else
cout<<"Failed to Rename\n";
}
}
};
I have created a class Scholar with attributes: string name, int id, char grade. Then, I had written the data in text file in binary mode using program P1. I had another program P2 which inserts a new data in between previous data.
It shows data (using program P1) when I initially created the text file with some objects. But, when I inserted a new data (using program P2), the attributes id and grade appears but, the attribute name went missing.
The Scholar class code:
#ifndef SCHOLAR_H
#define SCHOLAR_H
#include <iostream>
#include <cstdio>
using namespace std;
class Scholar {
int id;
string name;
char grade;
public:
void read_data() {
cout << "\nEnter ID: ";
cin >> id;
string temp;
getline(cin, temp);
cout << "Enter name: ";
getline(cin, name);
cout << "Enter grade: ";
cin >> grade;
}
void print_data() {
cout << "\nID: " << id << " | Name: " << name << " | Grade: " << grade;
}
int modify_data();
int _id() {
return id;
}
string _name() {
return name;
}
char _grade() {
return grade;
}
};
#endif // SCHOLAR_H
Program P1:
#include "MyHeaderFiles/Scholar.h"
#include <fstream>
#include <cstdlib>
#include <cctype>
int main() {
system("cls");
Scholar sch;
fstream fs;
fs.open("SchDB.txt", ios::out | ios::in | ios::binary | ios::trunc);
if(!fs) {
cerr << "File not found!";
system("PAUSE");
}
char reply;
do {
sch.read_data();
fs.write((char*) &sch, sizeof(sch));
cout << "Do you want to add another scholar (y/n) : ";
cin >> reply;
} while(tolower(reply) == 'y');
fs.seekg(0);
cout << "\nFile content\n------------" << endl;
while(!fs.eof()) {
fs.read((char*) &sch, sizeof(sch));
if(fs.eof()) break;
sch.print_data();
}
fs.close();
cout << endl;
return 0;
}
The initial image of output when I hadn't inserted any new data:
You can see the names!
Program P2:
#include "MyHeaderFiles/Scholar.h"
#include <fstream>
#include <cstdlib>
int main() {
system("cls");
Scholar sch;
Scholar newSch;
ofstream fout;
ifstream fin;
fout.open("Temp.txt", ios::out | ios::binary);
fin.open("SchDB.txt", ios::in | ios::binary);
char last = 'y';
int pos;
cout << "\nYou have to enter data of a new student." << endl;
newSch.read_data();
fin.seekg(0);
cout << "\nFile content\n------------" << endl;
while(!fin.eof()) {
pos = fin.tellg();
fin.read((char*) &sch, sizeof(sch));
if(sch._id() > newSch._id()) {
fout.write((char*) &newSch, sizeof(newSch));
last = 'n';
break;
} else {
fout.write((char*) &sch, sizeof(sch));
}
}
if(last == 'y') {
fout.write((char*) &newSch, sizeof(newSch));
} else if(!fin.eof()) {
fin.seekg(pos);
while(!fin.eof()) {
fin.read((char*) &sch, sizeof(sch));
if(fin.eof()) break;
fout.write((char*) &sch, sizeof(sch));
}
}
fin.close();
fout.close();
remove("SchDB.txt");
rename("Temp.txt", "SchDB.txt");
fin.open("SchDB.txt", ios::in | ios::binary);
fin.seekg(0);
while(!fin.eof()) {
fin.read((char*) &sch, sizeof(sch));
if(fin.eof()) break;
sch.print_data();
}
fin.close();
cout << endl;
return 0;
}
The later image when I used the program P2 to insert new data:
And, now you can see only the name attribute is missing!
I am using Code::Blocks IDE and GNU GCC Compiler.
Can anybody explain me why the string isn't showing up?
I'm learning C++ and I'm creating a simple C++ code in visual studio 2017 community. When the program read objects from a file then vs2017 gives an exception thrown.So how to solve this guys.
fstream File; Company Temp; try{ vector<Company>Object; // Company class name
cout << " 1. Show Data ";
cout << " 2. Put Data\n";
cout << " => ";
int a; cin >> a; cin.ignore(1000, '\n');
if (a == 1)
throw 5;
Temp.Get_Data();
Object.push_back(Temp);
File.open("Ma.bin", ios::binary | ios::out | ios::app);
int i = 0;
for (vector<Company>::iterator It = Object.begin(); It != Object.end(); It++) {
File.write((char *)&Object[i], sizeof(Object[i]));
i++;
}
File.close();
}
catch (int) {
Object.clear();
File.open("Ma.bin", ios::binary | ios::in);
File.seekg(0, ios::end);
auto total = File.tellg() / sizeof(Company);
cout << " total Object write " << total << "\n";
cout << " Which One you want to Dispaly ?"; int Number; cin >> Number; cin.ignore(1000, '\n');
int Position = (Number - 1) * sizeof(Company);
File.seekg(Position);
File.read((char *)&Temp, sizeof(Temp)); //this is the bug , if i comment this line then programme runs ok
Object.push_back(Temp);
File.close();
vector<Company>::iterator It = Object.begin();
It->Put_Data();
}
return 0;
}
Why does this file always contain an extra Fraction structure? If a user enters option 3 to view all fractions when the program just starts (the file should be empty), 0/0 is printed out. If a user selects option one and enters a fraction 1/1, and then selects option 3, two fractions are printed out 1/1 1/1.
Note: to run this you will need to create an empty .dat file called "fractions.dat"
I really appreciate your help!
#include <iostream>
#include <fstream>
using namespace std;
struct Fraction
{
int num, den;
};
int search(fstream& file, Fraction* f);
int menu();
void proccessChoice(int i);
Fraction* readFrac();
Fraction* fracs[100];
int index;
string fileName = "fractions.dat";
fstream file(fileName, ios::in | ios::out | ios::binary | ios::trunc);
//structure called Fraction with num and den as its only integer members
int main()
{
if (!file)
{
cout << "Error opening file. Program aborting.\n";
system("pause");
exit(1);
}
int choice;
do
{
choice = menu();
proccessChoice(choice);
} while(choice != 4);
system("pause");
return 0;
}
int menu()
{
int c;
cout << "1.Enter new fraction" << endl;
cout << "2.Display/update a fraction" << endl;
cout << "3.Display all fractions" << endl;
cout << "4.Quit" << endl;
cin >> c;
return c;
}
void proccessChoice(int i)
{
switch(i)
{
case 1:
{
cout << "Enter a fraction to add: ";
fracs[index] = readFrac();
file.seekp(0, ios::end);
file.write(reinterpret_cast<char*>(fracs[index]), sizeof(Fraction));
/*cout << fracs[index]->num << "/" << fracs[index]->den ;*/
index++;
}
break;
case 2:
{
cout << "Enter fraction to view/update: ";
Fraction* fToFind = readFrac();
int i = search(file, fToFind);
if (i == -1)
{
cout << "Fraction not found." << endl;
}
else
{
char r;
cout << fToFind->num << "/" << fToFind->den << " found at index " << i << ". Update? [y/n]";
cin >> r;
if(r == 'y' || r == 'Y')
{
cout << "Enter a new fraction: ";
Fraction* fToWrite = readFrac();
file.seekp(sizeof(Fraction) * (i));
file.write(reinterpret_cast<char*>(fToWrite), sizeof(Fraction));
}
}
cout << i << endl;
cout << "Case 2" << endl;
}
break;
case 3:
{
Fraction* cur = new Fraction();
//int pos = -1;
if (!file)
{
cout << "Error opening file. Program aborting.\n";
system("pause");
exit(1);
}
file.seekg(0, ios::beg);
while(!file.eof())
{
file.read(reinterpret_cast<char *>(cur), sizeof(Fraction));
cout << cur->num << "/" << cur->den << endl;
}
cout << "Case 3" << endl;
}
break;
}
}
int search(fstream& file, Fraction* f)
{
Fraction* cur = new Fraction();
int pos = -1;
if (!file)
{
cout << "Error opening file. Program aborting.\n";
system("pause");
exit(1);
}
file.seekg(0, ios::beg);
while(!file.eof())
{
file.read(reinterpret_cast<char *>(cur), sizeof(Fraction));
if((cur->num == f->num) && (cur->den == f->den))
{
cout << "\nFrac found!" << cur->num << "/" << cur->den<<endl;
pos = file.tellg()/sizeof(Fraction) - 1;
return pos;
}
}
return pos;
}
Fraction* readFrac()
{
Fraction* f = new Fraction();
char slash;
cin >> f->num >> slash >> f->den;
return f;
}
Attempted solution 1: works for the first attempt of the user to view all fractions but on the second attempt the file is not found.
case 3:
{
Fraction* cur = new Fraction();
//int pos = -1;
if (!file)
{
cout << "Error opening file. Program aborting.\n";
system("pause");
exit(1);
}
file.seekg(0, ios::beg);
while(!file.eof())
{
if(file.read(reinterpret_cast<char *>(cur), sizeof(Fraction)).gcount()== sizeof(Fraction))
{
cout << cur->num << "/" << cur->den << endl;
}
}
cout << "Case 3" << endl;
}
break;
}
Because you didn't yet reach the end of the file!
while(!file.eof())
You opened the empty file, however, note that the read cursor is currently at position 0. As long as you didn't attempt to read data file.eof() will be false, as the end of file hasn't been reached yet by the cursor.
You'll need to check whether you were actually able to extract the Fraction:
if(
file.read(reinterpret_cast<char *>(cur), sizeof(Fraction)).gcount()
== sizeof(Fraction)
){
// Fraction has been extracted
}
else
// either eof() or some other error.
Note that this gets much simpler if you provide a custom operator for this:
std::istream& operator>>(std:istream& in, Fraction& f){
return in.read(reinterpret_cast<char *>(&f), sizeof(Fraction));
}
// ....
while(file >> *cur){
// ... your code.
}