Usually they aren't used to write just a single number or a single character to file. They are usually used to write an array or an object to file. Here is an example of writing an object to file:
Code:
#include <iostream>
using std::cerr;
using std::endl;
using std::ios;
#include <fstream>
using std::ofstream;
// =============================
// Dummy Class for example
// =============================
class MyClass {
public:
MyClass(int n, char *s1, char *s2);
private:
int num;
char lastName[20];
char firstName[15];
};
// ==============================
// Main Function
// ==============================
int main()
{
ofstream outFile( "stuff.dat", ios::binary );
if( !outFile ) {
cerr << "File could not be opened." << endl;
exit( 1 );
}
MyClass object1(99, "Dade", "Murphy");
outFile.write( reinterpret_cast<const char *>(&object1), sizeof(MyClass) );
outFile.close();
return 0;
}
// ================================
// Class constructor
//=================================
MyClass::MyClass(int n, char *s1, char *s2)
{
num = n;
strcpy(lastName, s2);
strcpy(firstName, s1);
}