The Windows File Management 20





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:

  1. The application opens the Original.txt file by using CreateFile().
  2. The application retrieves a temporary file path and file name by using the GetTempPath() and GetTempFileName() functions, and then uses CreateFile() to create the temporary file.
  3. The application reads 64K blocks into a buffer, converts the buffer contents to uppercase, and writes the converted buffer to the temporary file.
  4. When all of Original.txt is written to the temporary file, the application closes both files, and renames the temporary file to Allcaps.txt by using the MoveFileEx() function.


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);



            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))



        return (2);



            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)



        return (3);



            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);



            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.



        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);




            fSuccess = WriteFile(hTempFile,buffer,dwBytesRead,&dwBytesWritten,NULL);


            if (!fSuccess)



                return (5);



                wprintf(LWriting to %s...\n, szTempName);





            return (6);


    } while (dwBytesRead == BUFSIZE);


    // Close the handles to the files.

    fSuccess = CloseHandle (hFile);

    if (!fSuccess)



       return (7);



       wprintf(LClosing hFile handle...\n);


    fSuccess = CloseHandle (hTempFile);

    if (!fSuccess)



       return (8);



        wprintf(LClosing hTempFile handle...\n);


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

    fSuccess = MoveFileEx(szTempName, pFileName, MOVEFILE_REPLACE_EXISTING);

    if (!fSuccess)



        return (9);




        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();









        (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);






Build and run the project. The following screenshot is a sample output without any argument.



Creating and Using a Temporary File Program Example: A sample console program output in action without any argument


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


Creating and Using a Temporary File Program Example: Creating a sample text file


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


Creating and Using a Temporary File Program Example: A sample console program output in action with the required 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.


Creating and Using a Temporary File Program Example: The second file was created successfully


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


Creating and Using a Temporary File Program Example: The content of the second file was converted to all capital letters


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.




< Windows Files 19 | Win32 Programming | Win32 File Index | Windows Files 21 >