Compare Two Word Documents in C++

·

2 min read

If you want to find out if there are any differences between two similar documents, MS Word offers the "Compare" function to help you make a quick comparison so that you can better manage and work with the documents. In this article, you will learn how to programmatically compare two Word documents in C++ using a C++ Word library.

Install the Library

The professional Word C++ library used is Spire.Doc for C++. It is designed for developers to create, read, write, convert, merge, split, and compare Word documents on any C++ platforms with fast and high-quality performance.
There are two methods to install it and you can refer to the below tutorial for details.
Integrate Spire.Doc for C++ in a C++ Application

Sample Code

Spire.Doc for C++ allows to compare two Word documents using Document->Compare() method. When opening the result, you can see all changes that have been made to the original document, including insertions, deletions as well as formatting modifications. The complete sample code is shown below.

#include "Spire.Doc.o.h"

using namespace Spire::Doc;

int main() {
    std::wstring file1 = L"Doc1.docx";
    std::wstring file2 = L"Doc2.docx";
    std::wstring outputFile = L"Output\\CompareDocuments.docx";

    //Load the first document
    intrusive_ptr<Document> doc1 = new Document();
    doc1->LoadFromFile(file1.c_str());

    //Load the second document
    intrusive_ptr<Document> doc2 = new Document();
    doc2->LoadFromFile(file2.c_str());

    //Compare the second document on the basis of the first document
    doc1->Compare(doc2, L"Jeremy");

    //Save as docx file.
    doc1->SaveToFile(outputFile.c_str(), Spire::Doc::FileFormat::Docx2013);
    doc1->Close();
    doc2->Close();

}