I am having this trouble - when I try to write binary of an integer to a file it doesn't write it in the Delivery file.
My whole idea was to take the integer, convert it to binary, write it to a file. After that if needed I'd come back to the program, write a new integer value and then add the new value to the already written one. i.e "5" in the file, come back, write "3" and then have 8 in the file.
Here is the code:
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
char answer;
struct PRODUCT {
string product_name;
int quantity;
PRODUCT() : product_name(""), quantity(0) {}
} product;
int main () {
fstream delivery_file("files/Delivery", ios::app | ios::in | ios::out | ios::binary);
do {
if (delivery_file.is_open()) {
cout << "\nPlease input the name of a product: ";
getline(cin, product.product_name);
cout << "\nPlease input the quantity of a product: ";
string str;
getline(cin, str);
product.quantity = atoi(str.c_str());
bool foundAndReplaced = false;
while (!delivery_file.eof())
{
PRODUCT temp_prod;
while (!delivery_file.eof())
{
char ch = delivery_file.get();
temp_prod.product_name += ch;
if (ch == 0)
{
break;
}
}
if (delivery_file.eof() && delivery_file.tellg() == ios::beg)
{
cout << "Error: Unexpected end of file.\n";
delivery_file.clear();
break;
}
if (temp_prod.product_name == product.product_name)
{
delivery_file.seekp(delivery_file.tellg());
delivery_file.read((char*)(temp_prod.quantity), sizeof(PRODUCT::quantity));
product.quantity += temp_prod.quantity;
delivery_file.write((char*)(product.quantity), sizeof(PRODUCT::quantity));
foundAndReplaced = true;
}
}
if (!foundAndReplaced)
{
delivery_file.write(product.product_name.c_str(), product.product_name.length() + 1);
delivery_file.write((char*)(&product.quantity), sizeof(product.quantity));
}
}
else {
cout << "Unable to open file";
}
cout << "Do you want to add more products? Y/N \n";
answer = 0;
while (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N')
{
answer = _getch();
}
}
while(answer == 'Y' || answer == 'y');
delivery_file.close();
cout << "\nDeliveries registered.\n";
return 0;
}