Et lille eksempel:
#include <iostream>
#include <fstream>
bool ReadIntBinary(int& someInt, const char* fileName)
{
std::ifstream file(fileName, std::ios::binary);
if(file && file.read((char *)&someInt, sizeof(someInt)))
return true;
return false;
}
bool WriteIntBinary(int& someInt, const char* fileName)
{
std::ofstream file(fileName, std::ios::binary);
if(file && file.write((char *)&someInt, sizeof(someInt)))
return true;
return false;
}
int main()
{
int n = -1;
// This is supposed to fail, the first time
if(ReadIntBinary(n, "pop.bin"))
std::cout << "Did Read: " << n << std::endl;
else
std::cout << "Failed read" << std::endl;
// Try to write it, should work
n = 1234;
if(WriteIntBinary(n, "pop.bin"))
std::cout << "Did write: " << n << std::endl;
else
std::cout << "Failed write" << std::endl;
n = 4321;
// This is supposed to work
if(ReadIntBinary(n, "pop.bin"))
std::cout << "Did Read: " << n << std::endl;
else
std::cout << "Failed read" << std::endl;
}