Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

File Processing using CreateFile, ReadFile and WriteFile Win32 APIs

1.  Introduction to CreateFile Win32 API

In this article, we will look at the example of using the CreateFile, ReadFile, WriteFile and OpenFile win32 API functions with an MFC Dialog based application. Win32 is a very rich API that supplies many functions and MFC is a Framework wrapped over those functions to form a logical working unit. Win32 API library is in a native format that means it is in C style (Procedural Approach) whereas MFC is an OOPS based Framework API. OK, let us start with the sample.

2. About Win32 File Copy Example

The below screenshot shows the sample application we will create in this article:

Win32 CreateFile Example

Win32 CreateFile Example

We set up the sample to copy the file text from source location to target location. The OS provides support for this plain file content copy work and this example is just for demo purpose. However, one can extend the task to transfer source content to target by skipping some words or adding something to the word, etc.

In the above sample, we can mention the filename to copy in the Source File Path. The Destination File Path text field holds target file name in which we need a copy of the source file content. The CopyFile Win32 API will do this task easily. However, in this article we will try the Win32 file processing functions CreateFile Win32, ReadFile, WriteFile and OpenFile. The sample is created using the VC++ Dialog-Based application.

Creating the dialog-based application is shown in the below video.

Once the dialog-based application is set up, we add control variables to the Edit boxes. The below video shows the steps:

3. Coding For The Win32 File API

3.1 Declaration of File Handles

First, we declare the win32 handles to the files and these handles are hcopysource, hCopyDest. Next, we declare the variables bytes_read, bytes_written to store the number of bytes read and written depending on the file processing operation. We also declare a char array to store the data read from the file temporarily.

//Sample 01: Declarations Required
HANDLE hcopysource, hCopyDest;
DWORD bytes_read, bytes_written;
CHAR buffer [4095];

3.2 Read User Input

Next, we read user input from the text box control variables to the string variables Source_file, Dest_file. The call to the GetWindowText function returns the text key-in in the text boxes.

//Sample 02: Get the User input
CString Source_file, Dest_file;
m_edit_ctrl_from.GetWindowText(Source_file);
m_edit_ctrl_to.GetWindowText(Dest_file);

3.3 CreateFile API & OPEN_EXISTING

The below code snippet uses the Win32 API function CreateFile to open the file entered by the user. The OPEN_EXISTING tag will tell the API to open the file when it already exits and fail otherwise. Once we open the file content which we will copy, we store the handle in the hcopysource. The GENERIC_READ flag for CreateFile tells that we are going to open the file for reading purpose.

//Sample 03: Create the Source File
hcopysource = ::CreateFile (Source_file, GENERIC_READ, 
  FILE_SHARE_READ, NULL, OPEN_EXISTING, 
  FILE_ATTRIBUTE_NORMAL, NULL);
if (hcopysource == INVALID_HANDLE_VALUE)
         AfxMessageBox("Unable to Open Source File");

3.4 CreateFile API & CREATE_ALWAYS

In the previous section, we stored a file handle for copy source. The same way we can store the destination file handle. Here it is expected that the file does not exist in the destination folder and we always try to create the file as a new file in the location specified. The flag GENERIC_WRITE tells that we will use this file for writing something on it. The CREATE_ALWAYS attribute tells that we will always create the file. If it doesn’t exist in the destination location, the API will create a new file and if it is there in that location, then the function will just open it. Therefore, the tag always creates the file and gives back the handle. Note we use the same CreateFile Win32 API for both reading and writing.

//Sample 04: Create Destination File
hCopyDest = ::CreateFile (Dest_file, GENERIC_WRITE, 
  0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 
  NULL);
if (hcopysource == INVALID_HANDLE_VALUE)
         AfxMessageBox("Unable to Destination Source File");

3.5 File Copy Using ReadFile & WriteFile

In this section, we write code to perform the file copy using ReadFile & WriteFile Win32 API functions. We use ReadFile Win32 API to read the data from the source file. Once the call succeeded, we will get the read content in the buffer variable. When the file content is over 4095 bytes, we will read its content in batches by making use of the loop. This means in each batch, we will read  4095 or less (That will be last read). The bytes_read  variable passed to ReadFile Win32 will tell us how many bytes are read from the source file. Say, for example, the file has 5000 bytes of data, and the first read batch will read all 4095 bytes and next batch will read the remaining 5 bytes in the next iteration. This way, we use the bytes_read variable when writing the data to the destination file using the API function WriteFile.

//Sample 05: Read the Source file content in a batch of 
//4095 or Lesser, then write to destination file
while (::ReadFile(hcopysource, buffer, 4095, &bytes_read, NULL) 
  && bytes_read > 0)
{
         ::WriteFile(hCopyDest, buffer, bytes_read, 
         &bytes_written, NULL);
         if (bytes_read != bytes_written)
         {
                 AfxMessageBox("Something Gone wrong while writing "
                  "to destination. Aborting the operation");
                 ::CloseHandle(hcopysource);
                 ::CloseHandle(hCopyDest);
                 return;
         }
}
AfxMessageBox("File contents copied to destination");

3.6 Cleanup

After completing the file copy action using ReadFile and WriteFile API functions, we close the file HANDLES. Then we display a message stating the content of the file copied to the target location.

//Sample 06: Do the Clean-Up work
m_edit_ctrl_from.SetWindowText("");
m_edit_ctrl_to.SetWindowText("");
::CloseHandle(hcopysource);
::CloseHandle(hCopyDest);

Below given video shows how the sample perform the file copy operation using the Win32 API Functions:

Source Code: Download Win32 CreateFile Example From Google Drive

Categories: Win32

Tags: , , , , , ,

Do you like this Example? Share your thoughts!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.