Oh and just a quick and dirty file write sample.
Code:
#include <windows.h>
#include <stdio.h>
// Random data structure (your own state vars would be here instead)
struct MYFILEDATA
{
int nSomeData;
BOOL bIsActive;
char data[20];
}
MYFILEDATA data;
DWORD dwWrite = 0;
// Fill in some values for the hell of it.
data.nSomeData = 1234;
data.bIsActive = TRUE;
for(int i=0;i<20;i++){data.data[i]=i;}
// Create a file, using the flag to always create it, even if a file already exists of the same name.
HANDLE hFile = CreateFile("settings.dat", GENERIC_WRITE, NULL, NULL, CREATE_ALWAYS, 0, NULL);
if(INVALID_HANDLE == hfile) // Make sure the handle to the file is valid.
{
// Something went wrong, maybe the file is read-only or some crap. Return E_FAIL so the app can take appropriate action.
return E_FAIL;
}
// Call WriteFile, passing the handle to the file, the address of the data to write out, and the size of the data to write in bytes,
// also passing in the address of dwWrite that WriteFile will fill in with the number of bytes written.
WriteFile(hFile, &data, sizeof(MYFILEDATA), &dwWrite, NULL);
if(sizeof(MYFILEDATA) != dwWrite) // Make sure that the number of bytes that dwWrite contains matches the size of the data that was attempted to be written.
{
CloseHandle(hFile); // Close the handle before returning.
return E_FAIL; // Failed to write, because dwData didn't match the size of the data. Maybe the disk was full or an I/O error occurred.
}
CloseHandle(hFile); // All done, close the file handle.
Keep in mind I didn't compile this so it may have errors, just typing off the top of my head. It just gives the jist of writing a simple struct to a file.