C++ code won\'t write to Binary File I have tried everything I can think of, I c
ID: 3831955 • Letter: C
Question
C++ code won't write to Binary File
I have tried everything I can think of, I cannot get my code to write to the Binary .dat file. This is a part of a much, much larger assignment with many other functions. I DO NOT want a complete code overhaul, which I've gotten before on here. What can I do to get my code to simply work. I understand that I haven't used the variables that were passed to the function. There are a few other unrelated things making my code dirty. I can fix those on my own, I just need to get my code writing to the file in binary. I will link the code here: https://codeshare.io/aYAdZR for better viewing
void createNewFile(fstream &invFile)
{
const int DESCRIPTION_SIZE = 26;
const int RECORD_DATE_SIZE = 10;
struct Inventory {
int recordID;
string description;
int quantity;
double wholesale;
double retail;
string date;
};
Inventory dummy;
fstream example("example.dat", ios::out | ios::binary);
dummy.recordID = 0;
dummy.description = "";
dummy.quantity = 0;
dummy.wholesale = 0.0;
dummy.retail = 0.0;
dummy.date = "";
for (int numberOfRecords = 0; numberOfRecords < 100; numberOfRecords++) {
example.write(reinterpret_cast(&dummy),sizeof(&dummy));
cout << "Now writing record " << (numberOfRecords + 1) << endl;
}
example.close();
}
Explanation / Answer
//Inclue header file fstream at the top
//for writting to file , you need to have ofstream not fstream, so declare function as below
void createNewFile(ofstream &example);
//function definition as below.
void createNewFile(ofstream &invFile)
{
const int DESCRIPTION_SIZE = 26;
const int RECORD_DATE_SIZE = 10;
struct Inventory {
int recordID;
string description;
int quantity;
double wholesale;
double retail;
string date;
};
Inventory dummy;
ofstream example("example.dat", ios::out | ios::binary);
dummy.recordID = 0;
dummy.description = "";
dummy.quantity = 0;
dummy.wholesale = 0.0;
dummy.retail = 0.0;
dummy.date = "";
for (int numberOfRecords = 0; numberOfRecords < 100; numberOfRecords++) {
example.write((char*)(&dummy), sizeof(dummy));
cout << "Now writing record " << (numberOfRecords + 1) << endl;
}
example.close();
}
//if solution provided helped ,please rate..thanks
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.