i am probably not including the ios::app correctly..... it won't let me append to the critters.bin file
Here is my code:
//header
struct Cat
{
char name[20];
int age;
};
///////////////////
#include <iostream>
#include <string>
#include "Cat.h"
#include <fstream>
using namespace std;
int main()
{
Cat yourCat;
int num = 3;
fstream file;
cout << "Enter 3 cat records.\n";
file.open("c:\\critters.bin", ios::out | 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(Cat));
}
while(file >> num)
{
file.write(reinterpret_cast<char*>(&yourCat), sizeof(Cat));
}
cout << "Record written to file.\n";
cout << "\n\nEnter one more cat\n";
file.open("critters.bin", ios::app);
cout << "NAME: ";
cin >> yourCat.name;
cout << "AGE: ";
cin >> yourCat.age;
file.write(reinterpret_cast<char*>(&yourCat), sizeof(Cat));
cout << "\n\nHere is a list of all cats:\n";
system("pause");
return 0;
}
Ive tried another approach and it still wont work:
#include <iostream>
#include <string>
#include "Cat.h"
#include <fstream>
using namespace std;
int main()
{
Cat yourCat;
Cat anotherCat;
ofstream file("c:\\critter.bin");
if(file.fail())
{ cerr << "Unable to open file for writing." << endl;
exit(1);
}
for(int i = 0; i < 3; i++)
{
cout << "Enter information about a cat:\n";
cout << "NAME: ";
cin >> yourCat.name;
file << yourCat.name << endl;
cout << "AGE: ";
cin >> yourCat.age;
file << yourCat.age << endl;
}
cout << "Record written to file\n";
file.close();
ofstream appendFile("critter.bin",ios_base::app);
if (appendFile.fail()) {
cerr << "Unable to open file for writing." << endl;
exit(1);
}
cout << "\n\nEnter another cat.\n";
cout << "NAME: ";
cin >> yourCat.name;
appendFile << yourCat.name;
cout << "AGE: ";
cin >> yourCat.age;
appendFile << yourCat.age << endl;
appendFile.close();
system("pause");
return 0;
}