開発環境 Microsoft Visual C++ 2010 Express (SP1)
実行環境 Microsoft Windows XP Home Edition (SP3)
プロジェクトの種類 Win32 コンソール アプリケーション
プロジェクト名 filecmp
アプリケーションの種類 コンソール アプリケーション
追加のオプション 空のプロジェクト

filecmp.c
#include <fcntl.h>	// _O_WTEXT
#include <io.h>		// _setmode
#include <stdio.h>	// _fileno
#include <string.h>	// memcmp
#include <tchar.h>
 
#define FIRST_SIZE	4096
#define SECOND_SIZE	(10 * 1024 * 1024)
 
int _tmain(int argc, _TCHAR *argv[])
{
	static char acBuf1[SECOND_SIZE];
	static char acBuf2[SECOND_SIZE];
	FILE *pFile1;
	FILE *pFile2;
	_TCHAR *ptcFile1;
	_TCHAR *ptcFile2;
	size_t sizeCount;
	size_t sizeRead1;
	size_t sizeRead2;
 
	_setmode(_fileno(stdout), _O_WTEXT);
	_setmode(_fileno(stderr), _O_WTEXT);
 
	if (argc != 3) {
		_ftprintf(stderr, _T("usage: filecmp file1 file2\n"));
		return 1;
	}
	ptcFile1 = argv[1];
	ptcFile2 = argv[2];
 
	if (_wfopen_s(&pFile1, ptcFile1, _T("rb")) != 0) {
		_ftprintf(stderr, _T("%s を開けません\n"), ptcFile1);
		goto Exit;
	}
	if (_wfopen_s(&pFile2, ptcFile2, _T("rb")) != 0) {
		_ftprintf(stderr, _T("%s を開けません\n"), ptcFile2);
		goto Exit;
	}
 
	_tprintf(_T("ファイル %s と %s を比較しています\n"), ptcFile1, ptcFile2);
	for (sizeCount = FIRST_SIZE; ; sizeCount = SECOND_SIZE) {
		sizeRead1 = fread(acBuf1, 1, sizeCount, pFile1);
		if (ferror(pFile1) != 0) {
			_ftprintf(stderr, _T("error: fread[%s]\n"), ptcFile1);
			goto Exit;
		}
		sizeRead2 = fread(acBuf2, 1, sizeCount, pFile2);
		if (ferror(pFile2) != 0) {
			_ftprintf(stderr, _T("error: fread[%s]\n"), ptcFile2);
			goto Exit;
		}
		if (sizeRead1 != sizeRead2) {
			_tprintf(_T("ファイルのサイズが違います\n"));
			break;
		}
		if (memcmp(acBuf1, acBuf2, sizeRead1) != 0) {
			_tprintf(_T("ファイルの内容が違います\n"));
			break;
		}
		if (sizeRead1 != sizeCount) {
			_tprintf(_T("相違点は検出されませんでした\n"));
			break;
		}
	}
Exit:
	_fcloseall();
	return 0;
}
 
最終更新:2012年08月31日 11:21