Creating and Using a Temporary File
The following example copies one file to another. The second file is an uppercase version of the first file.
The application opens the ORIGINAL.TXT file by using CreateFile. The application then obtains a temporary filename with the GetTempFileName function and uses CreateFile to create the temporary file. The application reads 4K blocks into a buffer, converts the buffer contents to uppercase, and writes the converted buffer to the temporary file. When all of ORIGINAL.TXT has been written to the temporary file, the application closes both files and renames the temporary file to ALLCAPS.TXT by using the MoveFile function.
HANDLE hFile;
HANDLE hTempFile;
DWORD dwBytesRead, dwBytesWritten, dwPos;
char szTempName[MAX_PATH];
char buffer[4096];
// Open the existing file.
hFile = CreateFile("ORIGINAL.TXT", // filename
GENERIC_READ, // open for reading
0, // do not share
NULL, // no security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE) {
ErrorHandler("Could not open file."); // process error
}
// Create a temporary file.
GetTempFileName("\\TEMP", // dir. for temp. files
"NEW", // temp. filename prefix
0, // create unique name
szTempName); // buffer for name
hTempFile = CreateFile((LPTSTR) szTempName, // filename
GENERIC_READ | GENERIC_WRITE, // open for read-write
0, // do not share
NULL, // no security
CREATE_ALWAYS, // overwrite existing file
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (hTempFile == INVALID_HANDLE_VALUE) {
ErrorHandler("Could not create temporary file.");
}
// Read 4K blocks to the buffer.
// Change all characters in the buffer to uppercase.
// Write the buffer to the temporary file.
do
{
if (ReadFile(hFile, buffer, 4096,
&dwBytesRead, NULL)) {
CharUpperBuff(buffer, dwBytesRead);
WriteFile(hTempFile, buffer, dwBytesRead,
&dwBytesWritten, NULL);
}
} while (dwBytesRead == 4096);
// Close both files.
CloseHandle(hFile);
CloseHandle(hTempFile);
// Move the temporary file to the new text file.
if (!MoveFile(szTempName, "ALLCAPS.TXT")) {
ErrorHandler("Could not move temp. file.");
}