If you want it in C++, it is better to write C++ code instead of C code:
// The headers to include are different
#include <iostream>
#include <fstream>
#include <string>
void menu();
int main() {
using namespace std;
ofstream fProduct;
string name;
int quantity;
int barcode;
double price;
// your menu, but for now we handle only the
// case 2: add a new product.
menu();
// as for now we deal only with the insertion of new
// products
// Let's open a new file using the C++ standard library
fProduct.open("Product.txt", ios::out | ios::app | ios::ate);
// If the write can be opened we continue, otherwise
// we skip the next part of the code
if (fProduct.is_open()) {
string conts = "y";
while (conts == "y") {
cout << "Name: "; cin >> name;
cout << "Quantity: "; cin >> quantity;
cout << "Barcode Number: "; cin >> barcode;
cout << "Price: "; cin >> price;
// Here we write in the file the information the user passed us.
// since we are getting information that should be written as
// sequence of char in the file, we could avoid to use
// int/double variables. Let's write in the file, comma
// separated
fProduct << name << "," << quantity << "," << barcode << "," << price << endl;
// Here we have some way to interrupt the loop
cout << "Add another product? [y/n]";
cin >> conts;
}
// Finally we close the file. (only if it was open...)
fProduct.close();
}
return 0;
}
// Your menu function using the standard streams
void menu() {
using namespace std;
cout << "1. List the products" << endl;
cout << "2. Add a new product" << endl;
cout << "3. Sell the new product" << endl;
cout << "4. Search by Barcode" << endl;
cout << "5. Exit" << endl;
}
and if you want it C it's better to use pure C code:
#include <stdio.h>
#include <string.h>
void menu();
int main() {
FILE *fProduct;
// again, all this variable could be simply char[].
char name[20];
int quantity, barcode;
double price;
// As for now our code handles only the insertion of
// new element, not the other choices of the menu
menu();
// Do not check if it is different than NULL,
// check only if it actually is something...
if (fProduct = fopen("Product.txt", "a")) {
char conts = 'y';
while (conts == 'y') {
printf("Name :"); scanf("%s", name);
printf("Quantity :"); scanf("%d", &quantity);
printf("Barcode Number :"); scanf("%d", &barcode);
printf("Price :"); scanf("%lf", &price);
// Let's write in the file
fprintf(fProduct, "%s,%d,%d,%lf\n", name, quantity, barcode, price);
getchar(); // chomps the last newline
printf("Add another product? [y/n] ");
conts = getchar();
}
// At the end of our loop we need to close the file.
fclose(fProduct);
}
return 0;
}
void menu() {
puts("1. List the products");
puts("2. Add a new product");
puts("3. Sell the new product");
puts("4. Search by Barcode");
puts("5. Exit");
}