Whenever I create a Temporary file in C++ Native WinAPI, the HANDLE returned is always INVALID_FILE_HANDLE but the temporary file has been created correctly?
Am I doing something wrong?
If I use GetLastError() the output is:
“The file exists”
In my code below I can successfully create a temporary file but the CreateFile function always returns INVALID_FILE_HANDLE and I can’t write any text to the file handle:
GetTempPath(dirLen, dir);
GetTempFileName(dir, fName, 0, tName);
HANDLE file = CreateFile(tName, GENERIC_WRITE, 0, NULL, CREATE_NEW,
FILE_ATTRIBUTE_TEMPORARY, NULL);
if (file == INVALID_HANDLE_VALUE) {
outputLastError(); // Outputs: "The file exists"
}
if (FAILED(WriteFile(file, (LPTSTR)toWrite.c_str(), strLen, 0, NULL))) {
cout << (_T("Failed to write string to file \r\n"));
outputLastError();
res = false;
}
// WriteFile doesn't fail but the temporary file is empty when I open it?
The
GetTempFileName()will always create the file:CREATE_NEWis then specified inCreateFile()(as already pointed out by Mat) causingCreateFile()to returnINVALID_FILE_HANDLE: