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

Updated on December 6, 2018
sirama profile image

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

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

Questions & Answers

    © 2018 sirama

    Comments

      0 of 8192 characters used
      Post Comment

      No comments yet.

      working

      This website uses cookies

      As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

      For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

      Show Details
      Necessary
      HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
      LoginThis is necessary to sign in to the HubPages Service.
      Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
      AkismetThis is used to detect comment spam. (Privacy Policy)
      HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
      HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
      Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
      CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
      Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
      Features
      Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
      Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
      Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
      Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
      Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
      VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
      PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
      Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
      MavenThis supports the Maven widget and search functionality. (Privacy Policy)
      Marketing
      Google AdSenseThis is an ad network. (Privacy Policy)
      Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
      Index ExchangeThis is an ad network. (Privacy Policy)
      SovrnThis is an ad network. (Privacy Policy)
      Facebook AdsThis is an ad network. (Privacy Policy)
      Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
      AppNexusThis is an ad network. (Privacy Policy)
      OpenxThis is an ad network. (Privacy Policy)
      Rubicon ProjectThis is an ad network. (Privacy Policy)
      TripleLiftThis is an ad network. (Privacy Policy)
      Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
      Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
      Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
      Statistics
      Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
      ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
      Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
      ClickscoThis is a data management platform studying reader behavior (Privacy Policy)