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 = L"Allcapfile.txt";

 

    if(argc != 2)

    {

        wprintf(L"Creating and using temporary file\n");

        wprintf(L"Usage: %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(L"First 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(L"GetTempPath()");

        return (2);

    }

      else

            wprintf(L"GetTempPath() - Windows temp path is:\n %s\n", lpPathBuffer);

 

    // Create a temporary file.

    uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files

                              L"NEW"// temp file name prefix

                              0,            // create unique name

                              szTempName);  // buffer for name

    if (uRetVal == 0)

    {

        DisplayErrorBox(L"GetTempFileName()");

        return (3);

    }

      else

            wprintf(L"GetTempFileName() - 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(L"Second 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(L"Reading 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(L"CharUpperBuffA() looks fine! Return %d\n", dwRetVal2);

            else

                DisplayErrorBox(L"CharUpperBuffA()");

 

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

 

            if (!fSuccess)

            {

                DisplayErrorBox(L"WriteFile()");

                return (5);

            }

            else

                wprintf(L"Writing to %s...\n", szTempName);

        }

        else

        {

            DisplayErrorBox(L"ReadFile()");

            return (6);

        }

    } while (dwBytesRead == BUFSIZE);

 

    // Close the handles to the files.

    fSuccess = CloseHandle (hFile);

    if (!fSuccess)

    {

       DisplayErrorBox(L"CloseHandle(hFile)");

       return (7);

    }

    else

       wprintf(L"Closing hFile handle...\n");

 

    fSuccess = CloseHandle (hTempFile);

    if (!fSuccess)

    {

       DisplayErrorBox(L"CloseHandle(hTempFile)");

       return (8);

    }

    else

        wprintf(L"Closing hTempFile handle...\n");

 

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

    fSuccess = MoveFileEx(szTempName, pFileName, MOVEFILE_REPLACE_EXISTING);

    if (!fSuccess)

    {

        DisplayErrorBox(L"MoveFileEx()");

        return (9);

    }

    else

    {

        wprintf(L"Moving (renaming) the %s to %s\n", szTempName, pFileName);

        wprintf(L"All 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, L"Error", MB_OK);

 

    LocalFree(lpMsgBuf);

    LocalFree(lpDisplayBuf);

}

 

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 >