How to create a FileCompare function by using Visual C++ .NET or Visual C++ 2005

Article translations Article translations
Article ID: 816189 - View products that this article applies to.
Expand all | Collapse all

SUMMARY

This step-by-step article describes how to compare two files to see if their contents are the same. This comparison looks at the contents of the two files, but does not at the file names, locations, dates, times, or other attributes.

This functionality is similar to the MS-DOS-based Fc.exe utility that is included with various versions of Microsoft Windows and Microsoft MS-DOS, and with some development tools.

The sample code that is described in this article performs a byte-by-byte comparison until a mismatch is found, or until the end of the file is reached. The code also performs the following two simple checks to increase the efficiency of the comparison:
  • If both file references point to the same file, the two files must be equal.
  • If the size of the two files different, the two files are different.

Create the Sample

  1. Start Visual Studio .NET (2003) or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C++ Projects under Project Types, and then click Empty Project (.NET) under Templates. Name the project FileCompare.

    Note In Visual Studio 2005, click Visual C++ under Project Types, and then click Empty Project under Templates.
  4. In Solution Explorer, right-click FileCompare, point to Add, and then click Add New Item.
  5. In the Add New Item dialog box, click Header File under Templates. In the Name text box, type Form1, and then click Open. The Form1.h file is displayed.
  6. Paste the following code in the Form1.h file:
    #pragma once
    #using <mscorlib.dll>
    #using <system.windows.forms.dll>
    #using <system.dll>
    #using <system.drawing.dll>
    
    namespace Compare
    {
    	using namespace System;
    	using namespace System::ComponentModel;
    	using namespace System::Collections;
    	using namespace System::Windows::Forms;
    	using namespace System::Drawing;
    	using namespace System::IO;
    
    	public __gc class Form1 : public System::Windows::Forms::Form
    	{	
    	public:
    		Form1(void)
    		{
    			InitializeComponent();
    		}
      
    	protected:
    		void Dispose(Boolean disposing)
    		{
    			if (disposing && components)
    			{
    				components->Dispose();
    			}
    			__super::Dispose(disposing);
    		}
    	
    	private: System::Windows::Forms::TextBox *  textBox1;
    	private: System::Windows::Forms::TextBox *  textBox2;
    	private: System::Windows::Forms::Label *  label1;
    	private: System::Windows::Forms::Label *  label2;
    	private: System::Windows::Forms::Button *  Compare;
    
    
    	private:
    
    		System::ComponentModel::Container * components;
    
    		
    		void InitializeComponent(void)
    		{
    			this->textBox1 = new System::Windows::Forms::TextBox();
    			this->textBox2 = new System::Windows::Forms::TextBox();
    			this->label1 = new System::Windows::Forms::Label();
    			this->label2 = new System::Windows::Forms::Label();
    			this->Compare = new System::Windows::Forms::Button();
    			this->SuspendLayout();
    			// 
    			// textBox1
    			// 
    			this->textBox1->Location = System::Drawing::Point(32, 104);
    			this->textBox1->Name = S"textBox1";
    			this->textBox1->TabIndex = 0;
    			this->textBox1->Text = S"";
    			// 
    			// textBox2
    			// 
    			this->textBox2->Location = System::Drawing::Point(168, 104);
    			this->textBox2->Name = S"textBox2";
    			this->textBox2->TabIndex = 1;
    			this->textBox2->Text = S"";
    			// 
    			// label1
    			// 
    			this->label1->Location = System::Drawing::Point(32, 64);
    			this->label1->Name = S"label1";
    			this->label1->TabIndex = 2;
    			this->label1->Text = S"File1";
    			// 
    			// label2
    			// 
    			this->label2->Location = System::Drawing::Point(176, 64);
    			this->label2->Name = S"label2";
    			this->label2->TabIndex = 3;
    			this->label2->Text = S"File2";
    			// 
    			// Compare
    			// 
    			this->Compare->Location = System::Drawing::Point(96, 168);
    			this->Compare->Name = S"Compare";
    			this->Compare->TabIndex = 4;
    			this->Compare->Text = S"Compare";
    			this->Compare->Click += new System::EventHandler(this, button1_Click);
    			// 
    			// Form1
    			// 
    			this->AutoScaleBaseSize = System::Drawing::Size(5, 13);
    			this->ClientSize = System::Drawing::Size(292, 273);
    			this->Controls->Add(this->Compare);
    			this->Controls->Add(this->label2);
    			this->Controls->Add(this->label1);
    			this->Controls->Add(this->textBox2);
    			this->Controls->Add(this->textBox1);
    			this->Name = S"Form1";
    			this->Text = S"Form1";
    			this->ResumeLayout(false);
    
    		}
    	private:
    		System::Void button1_Click(System::Object *  sender, System::EventArgs *  e)
    		{	 
    		}
    
    	};
    }
    This code creates a form that contains two text box controls and a command button.

    Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To add the common language runtime support compiler option in Visual C++ 2005, follow these steps:
    1. Click Project, and then click <ProjectName> Properties.

      Note <ProjectName> is a placeholder for the name of the project.
    2. Expand Configuration Properties, and then click General.
    3. Click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project setting in the right pane, click Apply, and then click OK.
    For more information about the common language runtime support compiler option, visit the following Microsoft Web site:
    /clr (Common Language Runtime Compilation)
    http://msdn2.microsoft.com/en-us/library/k8d11d4s.aspx
  7. Add the following function to the Form1 class:
    // This method accepts two strings that represent two files to 
    // compare. A return value of 0 indicates that the contents of the files
    // are the same. A return value of any other value indicates that the 
    // files are different.
    private:
    bool FileCompare(String *file1, String *file2)
    {
    	int file1byte;
    	int file2byte;
    	FileStream *fs1;
    	FileStream *fs2;
        
    	// Determine if the same file was referenced two times.
    	if (String::Equals(file1,file2))
    	{
    		// Return true to indicate that the files are the same.
    		return true;
    	}
    
            
    	// Open the two files.
    	try
    	{
    		fs1 = new FileStream(file1, FileMode::Open);
    		fs2 = new FileStream(file2, FileMode::Open);
    	
    			    
    		// Check the file sizes. If the sizes are different, the files 
    		// are different.
    		if (fs1->Length != fs2->Length)
    		{
    			// Close the file
    			fs1->Close();
    			fs2->Close();
    
    			// Return false to indicate files are different
    			return false;
    		}
    
    		// Read and compare a byte from each file until either a
    		// non-matching set of bytes is found or until the end of
    		// file1 is reached.
    		do 
    		{
    			// Read one byte from each file.
    			file1byte = fs1->ReadByte();
    			file2byte = fs2->ReadByte();
    		}
    		while ((file1byte == file2byte) && (file1byte != -1));
    
    		// Close the files.
    		fs1->Close();
    		fs2->Close();
    	}
    	
    	catch(Exception *ex)
    	{
    		if(fs1)
    		{
    			fs1->Close();
    		}
    		if(fs2)
    		{
    			fs2->Close();
    		}
    		throw ex;
    	}
    
    	// Return the success of the comparison. "file1byte" is 
    	// equal to "file2byte" at this point only if the files are 
    	// the same.
    	return ((file1byte - file2byte) == 0);
    }
    
    
  8. Paste the following code in the Click event of the button1_Click command button in the Form1 class:
    try
    {
    	if (FileCompare(this->textBox1->Text, this->textBox2->Text))
    	{
    		MessageBox::Show("Files are equal.");				
    	}
    	else
    	{
    		MessageBox::Show("Files are not equal.");
    	}
    }
    catch(Exception *ex)
    {
    	MessageBox::Show(ex->Message);
    }
    
  9. In Solution Explorer, right-click FileCompare, point to Add, and then click Add New Item.
  10. In the Add New Item dialog box, click C++ File under Templates. In the Name text box, type File_Compare, and then click Open. The File_Compare.cpp file is displayed.
  11. Paste the following code in the File_Compare.cpp file:
    #include "form1.h"
    
    #include <windows.h>
    #include <tchar.h>
    
    using namespace Compare;
  12. Add the following WinMain function to the File_Compare.cpp file:
    int APIENTRY _tWinMain(HINSTANCE hInstance,
                         HINSTANCE hPrevInstance,
                         LPTSTR    lpCmdLine,
                         int       nCmdShow)
    {
    }
  13. Paste the following code in the WinMain function:
    System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA;
    Application::Run(new Form1());
    return 0;
  14. Save the sample.

Run the Sample

  1. Supply full paths to two files in the text box controls.
  2. Click Compare.

REFERENCES

For more information, visit the following Microsoft Developer Network (MSDN) Web sites:
System.IO Namespace
File Access Through the FileStream Class

Properties

Article ID: 816189 - Last Review: November 26, 2007 - Revision: 2.3
APPLIES TO
  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET 2003 Standard Edition
  • Microsoft Visual C++ .NET 2002 Standard Edition
Keywords: 
kbhowtomaster kbhowto kbio KB816189

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com