Updated date:

File Processing Using Vc++ Win32 Mfc API Createfile, Readfile and Writefile

Author:

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like video games and reading books.

1. Introduction

In this article, we will look at the example of using the CreateFile and OpenFile win32 API functions with an MFC Dialog based application. Win32 is a rich API that supplies numerous functions and MFC is just a Framework wrapped over those functions to form logical functioning 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 the Example

Have a look at the below screenshot:

Win32 File Processing Example

Win32 File Processing Example

In this example, we write code to copy the file content from the source location to the destination location. Plain file content copy operation is already supported by the operating system. This example is to demonstrate how we use WIN32 API to perform a similar action. However, you one extend copy source content to destination by skipping specific words or adding something to a word, etc.

In this example, we specify the File name to be copied in the Source File Path and specify the Destination File name in the text box labeled Destination File Path. The CopyFile Win32 API will do this task easily. However, in this article we will explore the Win32 File processing functions. We create this example using the VC++ dialog based application.

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

Create the Application (No Audio)

After creating the dialog based MFC Application, we add control variables to the edit box controls. This is shown in the below video:

Add Control Variables (No Audio)

3) Copy Content Button Handler

1) First, the win32 handles to the files are declared and these handles are hcopysource, hCopyDest. Next, the variables bytes_read, bytes_written are used to store number of bytes read and written depending on the file processing operation. The buffer variable is used as the cache by the program to temporarily store the data read from the file.

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

2) Next, we read input entered by the user from the text box control variables. We store that to the string variables Source_file, Dest_file. The GetWindowText function returns the text keyed-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) The Win32 API function CreateFile is used to open the source 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 the file content we will copy is opened, we store its handle in the hcopysource. The GENERIC_READ flag tells that we 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");
	return;
}

4) The same way we 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.

//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 Open Destination File");
	return;
}

5) We use ReadFile API to read the data from the source file. Once the call succeeded, we will get the read content in the buffer variable. Note the usage of the while loop. When the file content is over 4095 bytes, the read operation will be continued in batches. We read 4095 or less (If it is less, that will be the last read) bytes in each batch. The bytes_read variable 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 the remaining 5 bytes are read 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)
	{
		CString msg;
		msg.Append("Something Gone wrong ");
		msg.Append("while writing to destination.");
		msg.Append(" Aborting the operation.");
		AfxMessageBox(msg);
		::CloseHandle(hcopysource);
		::CloseHandle(hCopyDest);
		return;
	}
}
AfxMessageBox("File contents copied to destination");

6) Once the Operation is completed, we close the file HANDLES opened by the button click event. We also display a message stating that the file content is copied to destination.

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

Copy file operation performed using the Win32 API - No Audio

Source Code: Download

© 2018 sirama