Open the file with OPEN_ALWAYS and check the error code to know if it has been created or an existing file has been opened:
// Clear error
SetLastError(0);
HANDLE hFile = CreateFile(fileName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_ALREADY_EXISTS)
{
// Read file here
}
else
{
// Ask for key and write file here
}
CloseHandle(hFile);
}
Alternatively check if the file exists and open it for reading or writing afterwards. This can be optimised by trying to open the file for reading and if that fails to open it for writing:
HANDLE hFile = CreateFile(fileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
// Read file here
}
else
{
hFile = CreateFile(fileName, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
// Ask for key and write file here
}
}
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);