No matter what I've tried it always says displays "File cannot be opened". |
If the file doesn't exist, it cannot be opened for input, that's why it fails. A simple fix, add
ios::trunc
to the open mode, it will discard any existing file contents, or create a new file if none exists.
The loop
while(!fio.eof())
would usually be inadvisable. In this case it seems to serve no purpose at all.
Just for demonstration purposes, I used two separate arrays here. That isn't necessary, but on the other hand, since you have the original array, there is no need for a file either. So, just as a somewhat useless example, this code writes the array to a file, reads it back into a different array, then displays the contents of that second array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
struct Reservation {
int id;
char name[30];
void AddCust() { }
void DisplayCust() const
{
cout << setw(10) << id << " " << name << '\n';
}
};
int main()
{
Reservation C[10] = {
{123, "Fred Bloggs"},
{456, "Suzy Smythe"},
{789, "Arthur Clarke"}
};
fstream fio ("Restaurant.bin", ios::in | ios::out | ios::binary | ios::trunc);
if (!fio)
{
cout << "\n \nFile cannot be opened. \n";
return 1;
}
int n = 3;
for (int i=0; i<n; i++)
{
fio.write(reinterpret_cast<char *>(& C[i]), sizeof(C[i]));
}
// Now display each customer's information from the binary file:
fio.seekg(0);
// system ("cls");
cout << "\n \nReservations made for the day: \n \n";
Reservation res[10];
int size = 0;
while (fio.read(reinterpret_cast<char *>(&res[size]), sizeof (Reservation)))
{
size++;
}
for (int i=0; i<size; ++i)
{
res[i].DisplayCust();
}
fio.close();
}
|
Note, I also used the C++ style cast - it does look a little more verbose, but it's good to get familiar with the C++ way of doing things.