5.2.3 Example: Creating and Using a Temporary File

The following code fragment copies one file to another so that the second file is an uppercase version of the first file.

The application opens the file ORIGINAL.TXT with 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 upper-case, 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 with the MoveFile function.

HANDLE hFile;

HANDLE hTempFile;

DWORD dwBytesRead, dwBytesWritten, dwPos;

char szTempName[MAX_PATH];

char buffer[4096];

/* Open existing file. */

hFile = CreateFile("ORIGINAL.TXT", /* filename */

GENERIC_READ, /* open for reading */

0, /* do not share */

(LPSECURITY_ATTRIBUTES) NULL, /* no security */

OPEN_EXISTING, /* existing file only */

FILE_ATTRIBUTE_NORMAL, /* normal file */

(HANDLE) NULL); /* no attr template */

if (hFile == INVALID_HANDLE_VALUE) {

ErrorHandler("Could not open file."); /* process err on fail*/

}

/* Create temporary file. */

GetTempFileName("\\TEMP", /* dir for temp files */

"NEW", /* temp filename prefix */

0, /* create unique name w/ sys time */

(LPTSTR) szTempName); /* buffer for name */

hTempFile = CreateFile((LPTSTR) szTempName, /* filename */

GENERIC_READ | GENERIC_WRITE, /* open for read/write */

0, /* do not share */

(LPSECURITY_ATTRIBUTES) NULL, /* no security */

CREATE_ALWAYS, /* overwrite existing */

FILE_ATTRIBUTE_NORMAL, /* normal file */

(HANDLE) NULL); /* no attr template */

if (hTempFile == INVALID_HANDLE_VALUE) {

ErrorHandler("Could not create temporary file."); /* process err */

}

/*

* Read 4K blocks to buffer.

* Change all characters in buffer to upper-case.

* Write the buffer to the temporary file.

*/

do {

if (ReadFile(hFile, (LPSTR) buffer, 4096, &dwBytesRead, NULL)) {

CharUpperBuff((LPTSTR) buffer, dwBytesRead);

WriteFile(hTempFile, (LPSTR) buffer, dwBytesRead,

&dwBytesWritten, NULL);

}

} while (dwBytesRead == 4096);

/* Close both files. */

CloseHandle(hFile);

CloseHandle(hTempFile);

/* Move temporary file to new text file. */

if (!MoveFile(szTempName, "ALLCAPS.TXT")) {

ErrorHandler("Could not move temp file.");

}