c语言 判断两个文件是否相同

使用strcmp比较:

#include 
#include 

int Compare(const char * file1, const char* file2)
{
	FILE* f1, * f2;
	int size1, size2;
	unsigned char buffer1[1024], buffer2[1024];
	f1 = fopen(file1, "rb+");
	f2 = fopen(file2, "rb+");



	size1 = fread(buffer1, 1, 1024, f1);
	size2 = fread(buffer2, 1, 1024, f2);
	
	printf("(%d)\n", size1);
	printf("(%d)\n", size1);


	printf("%s\n", buffer1);
	printf("%s\n", buffer2);


    if (strncmp(buffer1, buffer2, size1) == 0)
    {
        
        return 1;
    }


	fclose(f1);
	fclose(f2);
	return 0;
}


int main(int argc, char* argv[])
{
	if (Compare("1.txt", "2.txt"))
	{
		printf("文件内容相同!\n");
	}
	else
	{
		printf("文件内容不相同!\n");
	}
	return 0;
}

通过字节比较:

#include

int Compare(const char * file1, const char* file2)
{
	FILE* f1, * f2;
	int size1, size2;
	unsigned char buffer1[1024], buffer2[1024];
	f1 = fopen(file1, "rb+");
	f2 = fopen(file2, "rb+");
	int isTheSame = 0;
	if (!f1)
		goto end;
	if (!f2)
		goto end;
	while (1)
	{
		size1 = fread(buffer1, 1, 1024, f1);
		printf("(%s)\n", buffer1);
		size2 = fread(buffer2, 1, 1024, f2);
		if (size1 != size2)
		{
			goto end;
		}
		if (size1 < 1)
			break;
		for (int i = 0; i < size1; i++)
		{
			if (buffer1[i] != buffer2[i])
			{
				goto end;
			}
		}
	}
	isTheSame = 1;
end:
	if (f1)
		fclose(f1);
	if (f2)
		fclose(f2);
	return isTheSame;
}

int main(int argc, char* argv[])
{
	if (Compare("1.txt", "2.txt"))
	{
		printf("文件内容相同!\n");
	}
	else
	{
		printf("文件内容不相同!\n");
	}
	return 0;
}

你可能感兴趣的:(C语言,c语言,算法,linux)