Creating and Using a Temporary File Program Example
Applications can obtain unique file names for temporary files by using the GetTempFileName() function. The GetTempPath() function retrieves the path to the directory where temporary files should be created. The following procedure shows you how an application copies one file to another. To copy one file to another:
The following program example shows you the code how to copy one file to another, and notes that the target file is an uppercase version of the first file.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
// A safer version for string manipulation
#include <strsafe.h>
// A prototype that receives a function name, displaying
// system error code and its respective message
void DisplayErrorBox(LPTSTR lpszFunction);
#define BUFSIZE 512
int wmain(int argc, WCHAR *argv[])
{
HANDLE hFile;
HANDLE hTempFile;
DWORD dwRetVal, dwRetVal2;
DWORD dwBytesRead;
DWORD dwBytesWritten;
DWORD dwBufSize=BUFSIZE;
UINT uRetVal;
WCHAR szTempName[BUFSIZE];
char buffer[BUFSIZE];
WCHAR lpPathBuffer[BUFSIZE];
BOOL fSuccess;
LPWSTR pFileName = LAllcapfile.txt;
if(argc != 2)
{
wprintf(LCreating and using temporary file\n);
wprintf(LUsage: %s <file_to_be_read>\n, argv[0]);
// Non-zero means error
return -1;
}
// Open the existing file.
hFile = CreateFile(argv[1], // file name
GENERIC_READ, // open for reading
0, // do not share
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no template
if (hFile == INVALID_HANDLE_VALUE)
{
DisplayErrorBox(LFirst CreateFile());
return (1);
}
else
wprintf(L%s was successfully opened for reading!\n, argv[1]);
// Get the temp path.
dwRetVal = GetTempPath(dwBufSize, // length of the buffer
lpPathBuffer); // buffer for path
if (dwRetVal > dwBufSize || (dwRetVal == 0))
{
DisplayErrorBox(LGetTempPath());
return (2);
}
else
wprintf(LGetTempPath() - Windows temp path is:\n %s\n, lpPathBuffer);
// Create a temporary file.
uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
LNEW, // temp file name prefix
0, // create unique name
szTempName); // buffer for name
if (uRetVal == 0)
{
DisplayErrorBox(LGetTempFileName());
return (3);
}
else
wprintf(LGetTempFileName() - temp file name is:\n %s\n, szTempName);
// Create the new file to write the upper-case version to.
hTempFile = CreateFile((LPTSTR) szTempName, // file name
GENERIC_READ | GENERIC_WRITE, // open r-w
0, // do not share
NULL, // default security
CREATE_ALWAYS, // overwrite existing
FILE_ATTRIBUTE_NORMAL,// normal file
NULL); // no template
if (hTempFile == INVALID_HANDLE_VALUE)
{
DisplayErrorBox(LSecond CreateFile());
return (4);
}
else
wprintf(L%s was successfully created/overwritten\n for read & write!\n, szTempName);
// Read BUFSIZE blocks to the buffer. Change all characters in
// the buffer to upper case. Write the buffer to the temporary file.
do
{
if (ReadFile(hFile,buffer,BUFSIZE,&dwBytesRead,NULL))
{
wprintf(LReading from %s...\n, argv[1]);
// The following Unicode version fail, though the program runs without error
// dwRetVal2 = CharUpperBuff((LPWSTR)buffer, dwBytesRead);
// dwRetVal2 = CharUpperBuffW((LPWSTR)buffer, dwBytesRead);
dwRetVal2 = CharUpperBuffA(buffer, dwBytesRead);
if(dwRetVal2 = dwBytesRead)
wprintf(LCharUpperBuffA() looks fine! Return %d\n, dwRetVal2);
else
DisplayErrorBox(LCharUpperBuffA());
fSuccess = WriteFile(hTempFile,buffer,dwBytesRead,&dwBytesWritten,NULL);
if (!fSuccess)
{
DisplayErrorBox(LWriteFile());
return (5);
}
else
wprintf(LWriting to %s...\n, szTempName);
}
else
{
DisplayErrorBox(LReadFile());
return (6);
}
} while (dwBytesRead == BUFSIZE);
// Close the handles to the files.
fSuccess = CloseHandle (hFile);
if (!fSuccess)
{
DisplayErrorBox(LCloseHandle(hFile));
return (7);
}
else
wprintf(LClosing hFile handle...\n);
fSuccess = CloseHandle (hTempFile);
if (!fSuccess)
{
DisplayErrorBox(LCloseHandle(hTempFile));
return (8);
}
else
wprintf(LClosing hTempFile handle...\n);
// Move the temporary file to the new text file.
fSuccess = MoveFileEx(szTempName, pFileName, MOVEFILE_REPLACE_EXISTING);
if (!fSuccess)
{
DisplayErrorBox(LMoveFileEx());
return (9);
}
else
{
wprintf(LMoving (renaming) the %s to %s\n, szTempName, pFileName);
wprintf(LAll caps version of %s written to %s\n, argv[1], pFileName);
}
return (0);
}
void DisplayErrorBox(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message and clean up
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(WCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(WCHAR), L%s failed with error %d: %s, lpszFunction, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, LError, MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
Build and run the project. The following screenshot is a sample output without any argument.

Create a text file named tempfilexample.txt on C drive. Put some text and save it.

Re-run the project using the previously text file name as the argument.

If there is no error, the content of the first file will be written to the second file with all the text converted to the capital letters.

The following is the Allcapfile.txt file's content.

However in this program example, we fail for the Unicode version although the program runs without any error. It is found that the CharUpperBuffW() failed to do its job.