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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
#include <iostream>
#include <fstream>
using namespace std;
//the purpose of this program is to send structures into a file, and then read them from the same file
//structure to be written:
struct grades
{
int grade1;
int grade2;
int grade3;
int grade4;
}mygradesi,mygradeso,mygradesa;
int main ()
{
//declare pointers to structures for file io:
grades * mygradesptro=&mygradeso;
grades * mygradesptra=&mygradesa;
grades * mygradesptri;
//give the user options:
int answer;
do
{
cout<<"do u want to \n1, read from the file, or \n2, write over the file or \n3, append the file or \n4, exit the program?\n";
cin>>answer;
//option 1, read from the file:
if (answer==1)
{
//check the size of the file and allocate appropriate memory:
long begin,end;
ifstream myfilecheck ("binary.bin");
if (myfilecheck.is_open())
{
begin = myfilecheck.tellg();
myfilecheck.seekg (0, ios::end);
end = myfilecheck.tellg();
myfilecheck.close();
int filesize=(end-begin)/(sizeof(grades));
mygradesptri= new grades [filesize];
}
else cout << "Unable to open file for size check\n\n";
//read the file into memory:
int mygradesnum=0;
ifstream myfilei;
myfilei.open ("binary.bin", ios::in|ios::binary);
if (myfilei.is_open())
{
while ((myfilei.peek()!=EOF))
{
myfilei.read(reinterpret_cast<char*>(mygradesptri+mygradesnum*sizeof(grades)), sizeof(grades));
mygradesnum++;
}
//display memory on screen:
for(int i=0;i<mygradesnum;i++)
{
cout<<"\ngrade1\n"<< (mygradesptri[i]).grade1<<"\ngrade2\n"<< (mygradesptri[i]).grade2<<"\ngrade3\n"<< (mygradesptri[i]).grade3<<"\ngrade4\n"<< (mygradesptri[i]).grade4<<"\n\n";
}
}
else cout << "Unable to open file for input\n\n";
}
//option 2, write over the file:
if (answer==2)
{
ofstream myfileo;
myfileo.open ("binary.bin", ios::out|ios::binary);
cout << "please enter 4 grades separated by pressing enter\n";
cin >> (mygradesptro[0]).grade1 >> (mygradesptro[0]).grade2 >> (mygradesptro[0]).grade3 >> (mygradesptro[0]).grade4;
if (myfileo.is_open())
{
myfileo.write (reinterpret_cast<char*>(mygradesptro), sizeof(grades));
myfileo.close();
}
else cout << "Unable to open file for output\n\n";
}
//option 3, append the file:
if (answer==3)
{
ofstream myfilea;
myfilea.open ("binary.bin", ios::app|ios::binary);
cout << "please enter 4 grades separated by pressing enter";
cin >> (mygradesptra[0]).grade1 >> (mygradesptra[0]).grade2 >> (mygradesptra[0]).grade3 >> (mygradesptra[0]).grade4;
if (myfilea.is_open())
{
myfilea.write (reinterpret_cast<char*>(mygradesptra), sizeof(grades));
myfilea.close();
}
else cout << "Unable to open file for output\n\n";
}
//option 4, exit:
}while (answer!=4);
return 0;
}
|