Thiago R. Adams website

Home CodeBlog Articles Downloads Links Books About

Websites

Comparing two files (binary)

Function to compare if two files are identical.

bool IsFileEqual(const char *fileName1,  const char *fileName2)
{
  std::ifstream file1(fileName1, ios::in | ios::binary);
  std::ifstream file2(fileName2, ios::in | ios::binary);

  if (!file1.is_open())
  {
    std::stringstream ss;
    ss << "IsFileEqual: file not open: " << fileName1;
    throw std::exception(ss.str().c_str());
  }

  if (!file2.is_open())
  {
    std::stringstream ss;
    ss << "IsFileEqual: file not open: " << fileName2;
    throw std::exception(ss.str().c_str());
  }

  const int constBufferSize = 1000;
  char buffer1[constBufferSize];
  char buffer2[constBufferSize];

  for(;;)
  {
    file1.read(buffer1, constBufferSize);
    size_t readBytes1 = file1.gcount();

    if (file1.eof() && readBytes1 == 0)
      break;

    file2.read(buffer2, constBufferSize);
    size_t readBytes2 = file2.gcount();

    assert(readBytes2 > 0);
    if (readBytes1 != readBytes2)
      return false;

    if (_memicmp(buffer1, buffer2, min(readBytes1, readBytes2)) != 0)
      return false;
  }
  return true;
}

Want to see more? Go to the CodeBlog section.

About the author: I am Thiago Adams. I work as a professional C++ software engineer. I have created this website to share ideas and source code with other people with similar interests.
I would like to hear from you comments, critics, questions and suggestions about this topic or any other part of this website. Email: thiago.adams at gmail dot com