Creating temporary file: can't write to it
c++, winapi
Solution
The `GetTempFileName()` will always create the file:
If uUnique is zero, the function attempts to form a unique file name using the current system time. If the file already exists, the number is increased by one and the functions tests if this file already exists. This continues until a unique filename is found; the function creates a file by that name and closes it. Note that the function does not attempt to verify the uniqueness of the file name when uUnique is nonzero.
`CREATE_NEW` is then specified in `CreateFile()` (as already pointed out by Mat) causing `CreateFile()` to return `INVALID_FILE_HANDLE`:
CREATE_NEW Creates a new file, only if it does not already exist. If the specified file exists, the function fails and the last-error code is set to ERROR_FILE_EXISTS (80). If the specified file does not exist and is a valid path to a writable location, a new file is created.
Problem
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? ```