October 15th, 2012, 03:28 PM
#1
Save and Read struct help? binary file
here is my code:
/////////////////////////////////////////////struct
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Cat
{
char name[20];
int age;
};
//////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
#include "Cat.h";
int main()
{
Cat yourCat;
int NumStructs;
int num = 3;
int count = 0;
fstream file;
cout << "Enter 3 cat records.\n";
file.open("f:\\critters.bin", ios: ut | ios::binary);
for(int i = 0; i < 3; i++)
{
cout << "Enter information about a cat:\n";
cout << "NAME: ";
cin >> yourCat.name;
cout << "AGE: ";
cin >> yourCat.age;
file.write(reinterpret_cast<char*>(&yourCat), sizeof(struct Cat));
}
cout << "Record written to file.\n";
file.close();
cout << "\n\nEnter one more cat\n";
file.open("f:\\critters.bin", ios::app);
if (file.fail()) {
cerr << "Unable to open file for writing." << endl;
exit(1);
}
cout << "NAME: ";
cin >> yourCat.name;
cout << "AGE: ";
cin >> yourCat.age;
file.write(reinterpret_cast<char*>(&yourCat), sizeof(struct Cat));
file.close();
cout << "\n\nHere is a list of all cats:\n";
file.read(reinterpret_cast<char*>(&yourCat), sizeof(struct Cat));
for(int i = 0; i< 4;i++)
cout << setw(10) << left << yourCat.name <<endl;
cout << yourCat.age <<endl;
file.close();
system("pause");
return 0;
}
////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
//////////////////////////////////
.
I NEED HELP WITH THIS:
file.read(reinterpret_cast<char*>(&yourCat), sizeof(struct Cat));
for(int i = 0; i< 4;i++)
cout << setw(10) << left << yourCat.name <<endl;
cout << yourCat.age <<endl;
file.close();
//// i want to display all four records ...example:
Here is a list of all cats:
Tom 5
Fluffy 3
Sally 4
Sam 2
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Click Here to Expand Forum to Full Width
Bookmarks